Use a string from a config file to initilize a generic type [duplicate]

旧巷老猫 提交于 2019-12-21 20:18:22

问题


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>();

回答1:


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.



来源:https://stackoverflow.com/questions/7956094/use-a-string-from-a-config-file-to-initilize-a-generic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!