实例化具有运行时确定类型的对象 [英] Instantiate an object with a runtime-determined type

查看:18
本文介绍了实例化具有运行时确定类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实例化一个将在运行时确定的类型的对象.我还需要对该类型执行显式转换.

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);
}

这显然不是有效的代码,但我希望它传达了我正在尝试做的事情的本质.我实际使用的方法必须对大约 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.

另一种方法是使用反射:

Another way is to use reflection:

// 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()"它并返回类的实例,就像您使用了new"运算符一样.

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.

这篇关于实例化具有运行时确定类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆