问题描述
最近,我有这个问题。
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...
}
我认为这可以通过反射来完成某种方式..可能有一个更简单的方法。我一直在类型是如何工作的VS下盖类有些困惑。反正感谢您的帮助。
I think that this can be done with reflection somehow.. Possibly there's an easier way. I've been somewhat confused on how Type works vs Classes under the covers. Anyways thanks for any help.
感谢。
推荐答案
您想然后 Activator.CreateInstance
...但然后调用新创建的对象的方法将是非常棘手。理想情况下,你可以有一个非通用基础类或含有这些成员的接口:
You want Type.MakeGenericType
and then Activator.CreateInstance
... but then calling a method on the newly-created object will be tricky. Ideally you could have a non-generic base class or interface containing those members:
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 need to call a method which depends on the type parameter, you'll need to do that with reflection, or with dynamic
which can streamline reflection-based code.
编辑:cdhowie说,如果你总是实际的做的知道在编译时的类型,你可以使用一个通用的方法,这将让事情变得简单。那么你的呼叫的这样的方法:
As cdhowie says, if you always actually do know the type at compile-time, you can use a generic method which would make things much simpler. You'd then call the method like this:
DoSomething<int>();
DoSomething<MyClassA>();
DoSomething<MyClassB>();
这篇关于C#中如何初始化类型和QUOT的对象的一般类;类型"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!