繁体   English   中英

从 CLR 样式的类型全名获取 C# 样式的类型引用

[英]Get C#-style type reference from CLR-style type full name

Given a .NET type object found through reflection, is it possible to pretty print or decompile this type as a C# declaration, taking into account C# type aliases, etc.?

例如,

Int32 -> int
String -> string   
Nullable<Int32> -> int?
List<au.net.ExampleObject> -> List<ExampleObject>

我希望能够打印出接近源代码中最初编写的方法。

如果.NET框架里面什么都没有,有第三方库吗? 我可能会看看ILSpy

看到这个答案。

例子:

using System.CodeDom;
using System.CodeDom.Compiler;

CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

var typeRef = new CodeTypeReference("System.Nullable`1[System.Int32]");
string typeOutput = provider.GetTypeOutput(typeRef); // "System.Nullable<int>"

它将帮助您处理类似intstring的事情,以及 generics,但是您必须解决Nullable<T> -> T? 并自己using s。

别名被编译为它们的别名。 您永远不会知道源代码中它是string还是String ,坦率地说,我不明白为什么它很重要。

只有 15 个别名 (+Nullable) 只需在这些上使用 string.Replace。

这篇文章有 c# 源代码可以做到这一点: http://www.codeproject.com/Tips/621812/User-friendly-names-for-Types

另一篇文章中有类型声明的解决方案。 您可以轻松扩展它以支持类型别名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM