如何从字符串表示形式获取通用类型?

编程入门 行业动态 更新时间:2024-10-22 05:16:07
本文介绍了如何从字符串表示形式获取通用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有 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.

更多推荐

如何从字符串表示形式获取通用类型?

本文发布于:2023-11-08 13:49:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569546.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   形式   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!