使用类型对象来创建一个通用的 [英] Using a Type object to create a generic

查看:140
本文介绍了使用类型对象来创建一个通用的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个使用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 和<一href="http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.invoke.aspx">MethodBase.Invoke.

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

这篇关于使用类型对象来创建一个通用的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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