使用类型对象来创建一个通用的创建一个、对象、类型

由网友(若非深爱,请别靠近我)分享简介:我试图创建一个使用Type对象泛型类的一个实例。 I'm trying to create an instance of a generic class using a Type object. 基本上,我会在运行时不同类型的对象的集合,并且因为没有办法肯定知道是什么类型的,他们究竟会,我在想,我将不得不使用反射。...

我试图创建一个使用Type对象泛型类的一个实例。

I'm trying to create an instance of a generic class using a Type object.

基本上,我会在运行时不同类型的对象的集合,并且因为没有办法肯定知道是什么类型的,他们究竟会,我在想,我将不得不使用反射。

Basically, I'll have a collection of objects of varying types at runtime, and since there's no way for sure to know what types they exactly will be, I'm thinking that I'll have to use Reflection.

我工作是这样的:

Type elType = Type.GetType(obj);
Type genType = typeof(GenericType<>).MakeGenericType(elType);
object obj = Activator.CreateInstance(genType);

这是一个好主意。 ^ _ 的^

现在的问题是,我想访问我的GenericType℃的方法;>举例来说,我不能因为它的类型为对象类。我无法找到一个方法来丢obj的到特定GenericType&LT;>,因为这是摆在首位的问题(比如,我只是不能放像:)

The problem is, I'd like to access a method of my GenericType<> instance, which I can't because it's typed as an object class. I can't find a way to cast it obj into the specific GenericType<>, because that was the problem in the first place (i.e., I just can't put in something like:)

((GenericType<elType>)obj).MyMethod();

应该如何去解决这个问题?

How should one go about tackling this problem?

非常感谢! ^ _ 的^

Many thanks! ^_^

推荐答案

您将不得不继续使用反射来调用实际的方法:

You would have to continue using Reflection to invoke the actual method:

// Your code
Type elType = Type.GetType(obj);
Type genType = typeof(GenericType<>).MakeGenericType(elType);
object obj = Activator.CreateInstance(genType);

// To execute the method
MethodInfo method = genType.GetMethod("MyMethod",
    BindingFlags.Instance | BindingFlags.Public);
method.Invoke(obj, null);

有关更多信息,请参阅 Type.GetMethod 和MethodBase.Invoke.

For more information see Type.GetMethod and MethodBase.Invoke.

阅读全文

相关推荐

最新文章