我有 3 种类型,全部来自不同的 dll,你找不到如何在字符串中存储通用类型以及如何创建实例:
Type type1 = GetType1();
Type type2 = GetType2();
string strClassGenericType = "Namespace.ClassName<,>, DllName";
Type template = // How to get the generic template type?
Type genericType = template.MakeGenericType(new[] { type1, type2 });
object instance = Activator.CreateInstance(genericType);
我不确定 this符合我的要求。
请您参考如下方法:
在特定情况下,如果您希望对象的类型不知道其类型参数,则可以使用带有类型参数数量的反引号。下面是一个使用 Tuple 的例子:
Console.WriteLine(typeof (Tuple<,>).FullName); //For information only, outputs "System.Tuple`2"
var typeName = "System.Tuple`2";
var type = Type.GetType(typeName);
var generic = type.MakeGenericType(typeof (string), typeof (int));
Console.WriteLine(generic.FullName); //Outputs the type with the type parameters.
