Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

c# - Can Roslyn generate source code from an object instance?

Using the Roslyn API with Visual Studio 2015, can I convert an object instance to source code? Can I create an extension method like ".ToSourceCode()" as shown below?

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No. However, ILSpy can.

Based on the comments on the question and what I understand about Roslyn, decompilation is not supported. However, thanks to @Bradley's ILSpy tip, there is a solution:

  1. Download the ILSpy binaries from http://ilspy.net/
  2. Reference the following assemblies: ICSharpCode.Decompiler.dll, ILSpy.exe, Mono.Cecil.dll, ILSpy.BamlDecompiler.Plugin.dll
  3. Implement the ".ToSourceCode()" extension method as shown below:
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(), @"
|
", " "), @"s+", " ");
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...