[英]Passing Type to Method for Use in Generic
我试图了解为什么以下代码不起作用以及如何更改它以使其起作用。 简而言之,我试图将Type传递给方法,然后在声明List时使用该Type。
public void TestMethod(Type type)
{
List<type> items = new List<type>();
}
我收到错误消息:“'type'是变量,但像类型一样使用”
谢谢!
那将是:
public void TestMethod<T>()
{
List<T> items = new List<T>();
}
至于理论,评论中的人很好地解释了这一点。 您可以随时查看有关泛型的文档:)
您不能没有反思。 但是,您可以通过反射来实现。
string typeName = "System.String";
Type typeArg = Type.GetType(typeName);
Type genericClass = typeof(List<>);
Type newClass = genericClass.MakeGenericType(typeArg);
object created = Activator.CreateInstance(newClass);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.