【问题标题】:Get C#-style type reference from CLR-style type full name从 CLR 样式的类型全名获取 C# 样式的类型引用
【发布时间】:2011-09-09 21:49:54
【问题描述】:

给定一个通过反射找到的 .NET 类型对象,考虑到 C# 类型别名等,是否可以将该类型漂亮地打印或反编译为 C# 声明?

例如,

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

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

如果.NET 框架中什么都没有,是否有第三方库?我可能会看看ILSpy

【问题讨论】:

    标签: c# reflection types decompiling pretty-print


    【解决方案1】:

    There are only 15 aliases (+Nullable)。只需在这些上使用 string.Replace。

    【讨论】:

      【解决方案2】:

      请参阅this 答案。

      示例:

      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 之类的事情以及泛型,但是您必须自己解决 Nullable&lt;T&gt; -&gt; T?usings。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 我意识到这一点,我试图建议如果可能的话我更喜欢别名。
        【解决方案4】:

        another post 中有类型声明的解决方案。 您可以轻松扩展它以支持类型别名。

        【讨论】:

        • 是的,这就是我考虑查看 c# 反编译器源代码的原因。实际上,Jon Skeet 在另一个问题中提到了 CSharpCodeProvider。
        猜你喜欢
        • 1970-01-01
        • 2016-02-18
        • 1970-01-01
        • 1970-01-01
        • 2014-03-20
        • 2016-11-22
        • 2016-04-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多