我最近遇到了这个问题。
doSomething(typeof(int));
doSomething(typeof(MyClassA));
doSomething(typeof(MyClassB));
public void doSomething(Type _type)
{
var myGenObj = new MyGenericClass<_type>(); // Error. Really I'd want MyGenericClass<int>, MyGenericClass<MyClassA>, etc depending on what's passed in.
myGenObj.doSomeGenStuff();
// more stuff...
}
我认为这可以通过反思来完成。可能有一种更简单的方法。我对 Type 与 Class 的工作原理有些困惑。无论如何,感谢您的帮助。
Thanks.
你要Type.MakeGenericType http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx进而Activator.CreateInstance
...但是在新创建的对象上调用方法会很棘手。理想情况下,您可以拥有包含这些成员的非泛型基类或接口:
public interface IFoo
{
void CallSomeMethod();
}
public class MyGenericClass<T> : IFoo
{
...
}
// Names changed to be more conventional
public void DoSomething(Type type)
{
var genericType = typeof(MyGenericClass<>).MakeGenericType(type);
var instance = (IFoo) Activator.CreateInstance(genericType);
instance.CallSomeMethod();
}
If you do需要调用一个取决于类型参数的方法,您需要通过反射来做到这一点,or with dynamic
它可以简化基于反射的代码。
编辑:正如 cdhowie 所说,如果你总是实际上do在编译时知道类型,您可以使用通用方法,这将使事情变得更简单。那么你就会call像这样的方法:
DoSomething<int>();
DoSomething<MyClassA>();
DoSomething<MyClassB>();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)