实例化一个对象与运行时确定的类型实例、对象、类型

2023-09-02 21:23:47 作者:温柔范

我在一个情况下,我想实例化,将在运行时确定一个类型的对象。我还需要进行显式转换为该类型。

I'm in a situation where I'd like to instantiate an object of a type that will be determined at runtime. I also need to perform an explicit cast to that type.

事情是这样的:

static void castTest(myEnum val)
{
    //Call a native function that returns a pointer to a structure
    IntPtr = someNativeFunction(..params..);

    //determine the type of the structure based on the enum value
    Type structType = getTypeFromEnum(val);

    structType myStruct = (structType)Marshal.PtrToStructure(IntPtr, structType);
}

这显然不是有效的code,但我希望它传达了什么,我试图做的精髓。实际上,我工作的方法,将必须执行对〜35种不同类型的封送处理操作。我有需要做与同一组的类型类似的东西其它几种方法。所以,我想从这些方法分离出类型确定的逻辑,这样我只需要编写一次,所以该方法保持清洁和可读性。

This is obviously not valid code, but I hope it conveys the essence of what I'm trying to do. The method I'm actually working on will have to perform the marshaling operation on ~35 different types. I have several other methods that will need to do something similar with the same set of types. So, I'd like to isolate the type-determining logic from these methods so that I only need to write it once, and so that the methods stay clean and readable.

我必须承认自己是一个总的新手在设计。任何人都可以提出一个很好的办法处理这一问题呢?我怀疑有可能是因为我不知道适当的设计模式。

I must admit to being a total novice at design. Could anyone suggest a good approach to this problem? I suspect there might be an appropriate design pattern that I'm unaware of.

推荐答案

有几种方法可以创建某飞的对象,一个是:

There are several ways you can create an object of a certain type on the fly, one is:

// determine type here
var type = typeof(MyClass);

// create an object of the type
var obj = (MyClass)Activator.CreateInstance(type);

和你会得到OBJ MyClass的实例。

And you'll get an instance of MyClass in obj.

另一种方法是使用反射

// get type information
var type = typeof(MyClass);

// get public constructors
var ctors = type.GetConstructors(BindingFlags.Public);

// invoke the first public constructor with no parameters.
var obj = ctors[0].Invoke(new object[] { });

和从ConstructorInfo一回来,你就可以的invoke(),它与争论,回到一个类的实例,因为如果你已经使用了新的经营者。

And from one of ConstructorInfo returned, you can "Invoke()" it with arguments and get back an instance of the class as if you've used a "new" operator.