How can I get generic Type from a string representation?

前端 未结 5 741
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 00:42

I have MyClass.

And then I have this string s = \"MyClass\";. How can I get Type from the string s

5条回答
  •  春和景丽
    2020-11-30 01:44

    The format for generics is the name, a ` character, the number of type parameters, followed by a comma-delimited list of the types in brackets:

    Type.GetType("System.Collections.Generic.IEnumerable`1[System.String]");
    

    I'm not sure there's an easy way to convert from the C# syntax for generics to the kind of string the CLR wants. I started writing a quick regex to parse it out like you mentioned in the question, but realized that unless you give up the ability to have nested generics as type parameters the parsing will get very complicated.

提交回复
热议问题