标题有点晦涩。我想知道的是这是否可能:
string typeName = <read type name from somwhere>; Type myType = Type.GetType(typeName); MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>();
显然,MyGenericClass被描述为:
public class MyGenericClass<T>
现在,编译器抱怨“找不到类型或名称空间“ myType”。”必须有一种方法可以做到这一点。
您不能没有反思。但是,您 可以 通过反射来实现。这是一个完整的示例:
using System; using System.Reflection; public class Generic<T> { public Generic() { Console.WriteLine("T={0}", typeof(T)); } } class Test { static void Main() { string typeName = "System.String"; Type typeArgument = Type.GetType(typeName); Type genericClass = typeof(Generic<>); // MakeGenericType is badly named Type constructedClass = genericClass.MakeGenericType(typeArgument); object created = Activator.CreateInstance(constructedClass); } }
注意:如果泛型类接受多种类型,则在省略类型名称时必须包含逗号,例如:
Type genericClass = typeof(IReadOnlyDictionary<,>); Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);