从配置文件使用一个字符串,用来初始化一个泛型类型 [英] Use a string from a config file to initilize a generic type
问题描述
我有一个类:
公共类MyClass的< T>
我有我读一个配置文件有,比方说,的Guid
的类型 T
。
我如何做到这一点,除了使用字符串从配置文件,而不是实际的类型(而不是硬编码的Guid
)?
MyClass的<&的Guid GT; =新MyClass的<&的Guid GT;();
您需要完全限定的类型名称>
VAR typeArgument = Type.GetType(的System.Guid);
然后你可以使用反射来获取参数化类型:
VAR genericType = typeof运算(MyClass的<>)MakeGenericType(typeArgument)。
然后你就可以通过实例:
VAR实例= Activator.CreateInstance(genericType);
但我不知道你为什么会想这样做或为什么它会在是有益的场景。由于使用这种技术,你将永远无法与之交互 MyClass的< T>
,其中 T
的定义是什么你在编译时指定,你失去大部分摆在首位使用泛型的优势。
I have a class:
public class MyClass<T>
I have a config file that I am reading that has, say, Guid
for the type T
.
How do I do this, except using the string from the config file instead of the actual type (instead of hard-coding Guid
)?
MyClass<Guid> = new MyClass<Guid>();
You need the fully qualified type name:
var typeArgument = Type.GetType("System.Guid");
Then you can use reflection to get the parameterized type:
var genericType = typeof(MyClass<>).MakeGenericType(typeArgument);
Which you can then instantiate via:
var instance = Activator.CreateInstance(genericType);
But I'm not sure why you would want to do this or why it would be useful in your scenario. Since using this technique, you'll never be able to interact with MyClass<T>
where T
is defined as something you're specifying at compile-time, you lose most of the advantages of using generics in the first place.
这篇关于从配置文件使用一个字符串,用来初始化一个泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!