如何从字符串表示形式获取通用类型? [英] How can I get generic Type from a string representation?

查看:87
本文介绍了如何从字符串表示形式获取通用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 MyClass< T>

然后我有这个字符串s = MyClass< AnotherClass>; 。如何从字符串 s 中获取Type?

And then I have this string s = "MyClass<AnotherClass>";. How can I get Type from the string s?

一种方法(难看)是解析出< ;和>,然后执行以下操作:

One way (ugly) is to parse out the "<" and ">" and do:

Type acType = Type.GetType("AnotherClass");  
Type whatIwant = typeof (MyClass<>).MakeGenericType(acType);

但是有没有一种更干净的方法来获取最终类型而不进行任何解析等?

But is there a cleaner way to get the final type without any parsing, etc.?

推荐答案

泛型格式是名称,字符,类型参数的数量,后跟以逗号分隔的类型列表:

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]");

我不确定是否有简单的方法可以将C#语法从泛型转换为CLR想要的字符串。我开始写一个快速的正则表达式来解析它,就像您在问题中提到的那样,但是意识到除非您放弃使用嵌套泛型作为类型参数的功能,否则解析将变得非常复杂。

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.

这篇关于如何从字符串表示形式获取通用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆