![](/img/trans.png)
[英]Pass an instance of a generic type as a parameter on a dynamic instance of a generic class
[英]Can a type parameter of a generic class be set dynamically through a Type instance?
我想做类似下面的代码。
public IList SomeMethod(Type t)
{
List<t> list = new List<t>;
return list;
}
当然,这是行不通的。 我还有其他方法可以使用对Type实例的引用来动态设置泛型类的type参数吗?
尝试这个:
public IList SomeMethod(Type t)
{
Type listType = typeof(List<>);
listType = listType.MakeGenericType(new Type[] { t});
return (IList)Activator.CreateInstance(listType);
}
您必须将Type.MakeGenericType()
方法与Activator.CreateInstance()
一起使用。
生成的代码丑陋,缓慢,并且使您无法正常运行在编译时通常会捕获的错误。 这些都不是什么大不了的事,但是我已经看到最后一个特别使其他.Net开发人员(他们期望完全类型安全)措手不及。
就我个人而言,我从来没有这样做过。 每当我受到诱惑时,我就把它当作是我的设计有问题的一种征兆,然后再回到制图板上。 我没有后悔那门课。
这里没有其他信息,仅适用于那些遵循以下沙盒代码的程序(我不得不全部尝试)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListFromType
{
class Program
{
static void Main(string[] args)
{
var test1 = FlatList(typeof(DateTime));
var test2 = TypedList<DateTime>(typeof(DateTime));
}
public static IList<T> TypedList<T>(Type type)
{
return FlatList(type).Cast<T>().ToList();
}
public static IList FlatList(Type type)
{
var listType = typeof(List<>).MakeGenericType(new Type[] { type });
var list = Activator.CreateInstance(listType);
return (IList) list;
}
}
}
你能尝试像下面这样吗,它是泛型类型,
public IList SomeMethod<T>(T t)
{
List<T> list = new List<T>();
list.Add(t);
return list;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.