我怎样才能仿制类型从字符串再presentation [英] How can I get generic Type from string representation

查看:163
本文介绍了我怎样才能仿制类型从字符串再presentation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MyClass的< T>

然后,我有这个字符串s =MyClass的< AnotherClass>中;

如何从字符串s拿到类型?

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

单向(丑陋的)是解析出&LT;和>,并做到:

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. ? Thanks.

推荐答案

仿制药格式>是名字,一个`性格,类型参数的数目,后面括号中的类型的逗号分隔的列表:

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.

这篇关于我怎样才能仿制类型从字符串再presentation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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