Getting a specific method source code from .cs fil

2019-01-25 21:31发布

1 - I have this file content on the disc (cs file, not compiled):

    namespace Test
    {
        using System;
        public class TestClass 
        {
            public string SomeTestMethod(){
                return "test here";
            }
        }
    }

How do I get in run time into a variable the method:

public string SomeTestMethod(){
    return "test here";
}

for example: SourceCodeParser.GetMothod("path to file","SomeTestMethod");

2 - Is it possible the content of accessor member?

   public string SomeMember {
        get {
            return "test here";
        }
    }

标签: c# parsing
3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-25 22:05

Roslyn is what you need. You can easily install it using nuget. Here is a working code for getting a method body:

string GetMethod(string filename, string methodName)
{
    var syntaxTree = SyntaxTree.ParseFile(filename);
    var root = syntaxTree.GetRoot();
    var method = root.DescendantNodes()
                     .OfType<MethodDeclarationSyntax>()
                     .Where(md => md.Identifier.ValueText.Equals(methodName))
                     .FirstOrDefault();
    return method.ToString();
}

and code for getting body of property getter:

string GetPropertyGetter(string filename, string propertyName)
{
    var syntaxTree = SyntaxTree.ParseFile(filename);
    var root = syntaxTree.GetRoot();
    var property = root.DescendantNodes()
                       .OfType<PropertyDeclarationSyntax>()
                       .Where(md => md.Identifier.ValueText.Equals(propertyName))
                       .FirstOrDefault();
    var getter = property.AccessorList.Accessors.First(a => a.Kind == SyntaxKind.GetAccessorDeclaration);
    return getter.ToString();
}
查看更多
冷血范
3楼-- · 2019-01-25 22:05

You need a tool that can parse the source code, tracks code locations, and knows how to look up methods (or variables, or whatever named thing you care about) in the source code. With that, finding the lines of interest is pretty easy. Such a tool isn't easy to build because parsers for full languages aren't easy to build. Nor are the lookup functions easy; parameters, namespaces, templates, inheritance all combine to make name lookup for modern languages remarkably complex.

Program transformation (PT) tools (which often have such full parsers already available) often do this by building an AST in memory which represents the code. Then, given rules for name lookup, finding the code in the AST by name is relatively straightforward, and one can use the prettyprinter function of such a tool to pretty print the named-entity into a buffer/string/diskfile wherever you want it parked.

You are not likely to find a PT as a subroutine you can call from C# directly. You may be able to invoke such a tool from your program, and have it return the string as a text result/in a file/via a pipe whatever you thinks is best for interprocess communication.

If you want to show the method text embedded in an HTML page, you can often configure the PT to generate the entire page containing the prettyprinted entity text. (See the JavaSource browser via my bio for an example like this).

查看更多
趁早两清
4楼-- · 2019-01-25 22:16

The .NET Reflection class does not support decompiling to C#. The best you can do is use MMethodInfo.GetMethodBody() and call MethodBody.GetILAsByteArray() on the response. That will give you the MSIL which is the best that .NET reflection can give you.

To decompile to C# you will need a decompiler - of which there are at least a dozen legitimate options. You'll need to investigate for one that meets your requirements and budget.

One option is Red Gate's .NET Reflector. Nick Harrison has a long and thorough article on using .NET Reflector in an application to render source code as HTML.

查看更多
登录 后发表回答