标题有点晦涩。我想知道的是这是否可能:
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);