Roslyn 可以从对象实例生成源代码吗? [英] Can Roslyn generate source code from an object instance?
本文介绍了Roslyn 可以从对象实例生成源代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Visual Studio 2015 中使用 Roslyn API,我可以将对象实例转换为源代码吗?我可以创建一个像.ToSourceCode()"这样的扩展方法,如下所示?
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);
}
}
推荐答案
没有.但是,ILSpy 可以.
No. However, ILSpy can.
根据对问题的评论以及我对 Roslyn 的了解,不支持反编译.但是,感谢@Bradley 的 ILSpy 提示,有一个解决方案:
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:
- 从 http://ilspy.net/ 下载 ILSpy 二进制文件
- 参考以下程序集:ICSharpCode.Decompiler.dll、ILSpy.exe、Mono.Cecil.dll、ILSpy.BamlDecompiler.Plugin.dll
- 实现.ToSourceCode()"扩展方法,如下所示:
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+", " ");
}
}
这篇关于Roslyn 可以从对象实例生成源代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文