Roslyn可以从对象实例生成源代码吗?

时间:2015-04-10 17:36:45

标签: c# roslyn vs-2015-preview

在Visual Studio 2015中使用Roslyn API,我可以将对象实例转换为源代码吗?我可以创建一个类似" .ToSourceCode()"的扩展方法。如下图所示?

class Foo { }
class Program
{
    static string classSourceCode = "class Foo { }";
    static void Main()
    {
        var instance = new Foo();
        var instanceSourceCode = instance.GetType().ToSourceCode();
        System.Diagnostics.Debug.Assert(instanceSourceCode == classSourceCode);
    }
}

1 个答案:

答案 0 :(得分:10)

没有。但是,ILSpy可以。

根据对问题的评论以及我对Roslyn的理解,不支持反编译。但是,感谢@ Bradley的ILSpy提示,有一个解决方案:

  1. http://ilspy.net/
  2. 下载ILSpy二进制文件
  3. 引用以下程序集:ICSharpCode.Decompiler.dll,ILSpy.exe,Mono.Cecil.dll,ILSpy.BamlDecompiler.Plugin.dll
  4. 实施" .ToSourceCode()"扩展方法如下图所示:
  5. using System;
    using System.Linq;
    using System.Reflection;
    using System.Text.RegularExpressions;
    using ICSharpCode.Decompiler;
    using ICSharpCode.ILSpy;
    using Mono.Cecil;
    class Foo { }
    class Program
    {
        static string classSourceCode = "using System; internal class Foo { } ";
        static void Main()
        {
            var instance = new Foo();
            var instanceSourceCode = instance.GetType().ToSourceCode();
            System.Diagnostics.Debug.Assert(instanceSourceCode == classSourceCode);
        }
    }
    
    static class TypeExtensions
    {
        public static string ToSourceCode(this Type source)
        {
            var assembly = AssemblyDefinition.ReadAssembly(Assembly.GetExecutingAssembly().Location);
            var type = assembly.MainModule.Types.FirstOrDefault(t => t.FullName == source.FullName);
            if (type == null) return string.Empty;
            var plainTextOutput = new PlainTextOutput();
            var decompiler = new CSharpLanguage();
            decompiler.DecompileType(type, plainTextOutput, new DecompilationOptions());
            return Regex.Replace(Regex.Replace(plainTextOutput.ToString(), @"\n|\r", " "), @"\s+", " ");
        }
    }