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

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

问题描述

我有 MyClass.

然后我有这个 string s = "MyClass";.如何从字符串 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天全站免登陆