从类型参数创建泛型类实例 [英] Creating a generic class instance from a type parameter

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

问题描述

说我们有一个像这样的课程:

Say we have a class like this :

public class someclass<T> : Iinterface {}


我们有一个像这样的功能:


And we have a function like this:

public Iinterface Create(Type type)
{
// how to return ?
}


推荐答案

Type finalType = typeof(someclass<>);
return Activator.CreateInstance(finalType.MakeGenericType(type));



另请参见此博客 [



See also this blog[^] which a Google search turned up.


请参阅:
C#2.0中的泛型 [
see this:
Generics in C# 2.0[^]


反射使您可以动态创建对象:
Reflection allows you to create objects dynamically:
string myType = "MyNamespace.MyClass";
Assembly asm = Assembly.GetExecutingAssembly();
Type t = asm.GetType(myType);
Object o = Activator.CreateInstance(t, null, null);

因此,在您的情况下,您只需要最后一行.

So in your case, you would need just the last line.


这篇关于从类型参数创建泛型类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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