简体   繁体   English

如何用罗琳得到一种方法的身体?

[英]How to get il of one method body with 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 我想在我的C#源代码文件中获取一种方法的信息,我已经用roslyn打开解决方案并找到如下所示的方法符号

Roslyn.Compilers.Common.ISymbol s=GetMethodSymbolAtPosition (30);

I have an ISymbol how get il now? 我有一个ISymbol,现在怎么知道?

Unfortunately, the IL generation is entirely hidden inside the Emit call in Roslyn. 不幸的是,IL生成完全隐藏在Roslyn的Emit调用中。 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();

where method is your ISymbol . method是您的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. 在更复杂的情况下,您可能需要发出整个/初始编译,并通过反射获取生成的方法。

Refer to this post to find out what you can do with the results of GetMethodBody() . 请参阅这篇文章,以了解如何使用GetMethodBody()的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM