如何用罗琳得到一种方法的身体? [英] How to get il of one method body with roslyn?
问题描述
我想在我的C#源代码文件中找到一种方法,我已经用roslyn打开解决方案并找到如下所示的方法符号
I want to get il of one method in my c# source code file.I have opened solution with roslyn and find the method symbol like below
Roslyn.Compilers.Common.ISymbol s=GetMethodSymbolAtPosition (30);
我有一个ISymbol,现在怎么会患病?
I have an ISymbol how get il now?
推荐答案
不幸的是,IL生成完全隐藏在Roslyn的 Emit
调用中.但我给您一个简单的入门方法.
Unfortunately, the IL generation is entirely hidden inside the Emit
call in Roslyn. But I'll give a simple to get you started.
假设您从现有的编译开始:
Let's suppose you start of with an existing compilation:
var initial = CSharpCompilation.Create("Existing")
.AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(@"
namespace Test
{
public class Program
{
public static void HelloWorld()
{
System.Console.WriteLine(""Hello World"");
}
}
}"));
var method = initial.GetSymbolsWithName(x => x == "HelloWorld").Single();
其中 method
是您的 ISymbol
.然后您可以执行以下操作:
where method
is your ISymbol
. Then you can do following:
// 1. get source
var methodRef = method.DeclaringSyntaxReferences.Single();
var methodSource = methodRef.SyntaxTree.GetText().GetSubText(methodRef.Span).ToString();
// 2. compile in-memory as script
var compilation = CSharpCompilation.CreateScriptCompilation("Temp")
.AddReferences(initial.References)
.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(methodSource, CSharpParseOptions.Default.WithKind(SourceCodeKind.Script)));
using (var dll = new MemoryStream())
using (var pdb = new MemoryStream())
{
compilation.Emit(dll, pdb);
// 3. load compiled assembly
var assembly = Assembly.Load(dll.ToArray(), pdb.ToArray());
var methodBase = assembly.GetType("Script").GetMethod(method.Name, new Type[0]);
// 4. get il or even execute
var il = methodBase.GetMethodBody();
methodBase.Invoke(null, null);
}
在更复杂的情况下,您可能需要发出整个/初始编译,并通过反射获取生成的方法.
In a more complex case, you'd probably need to emit the entire/initial compilation, and get the generated method via reflection.
请参阅此发布以找出您可以对 GetMethodBody()
的结果执行的操作.
Refer to this post to find out what you can do with the results of GetMethodBody()
.
这篇关于如何用罗琳得到一种方法的身体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!