C#中如何初始化类型和QUOT的对象的一般类;类型" [英] C# How to Initialize Generic class with object of type "Type"

查看:177
本文介绍了C#中如何初始化类型和QUOT的对象的一般类;类型"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我有这个问题。

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.

感谢。

推荐答案

您想 Type.MakeGenericType 然后 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的对象的一般类;类型&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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