How to get method definition using Roslyn?

房东的猫 提交于 2019-12-05 12:33:38

I'm assuming you don't need the fully qualified name. If you do, you'll have to use the SemanticModel API instead of the Syntax API.

To display the name of a method, cast to MethodDeclarationSyntax and use the Identifier property.

To display the name of a property, cast to PropertyDeclarationSyntax and use the Identifier property.

var tree = CSharpSyntaxTree.ParseText(@"
public class Sample
{
    public string FooProperty {get; set;}
   public void FooMethod()
   {
   }
}");

var members = tree.GetRoot().DescendantNodes().OfType<MemberDeclarationSyntax>();

foreach (var member in members)
{
    var property = member as PropertyDeclarationSyntax;
    if (property != null)
        Console.WriteLine("Property: " + property.Identifier);
    var method = member as MethodDeclarationSyntax;
    if (method != null)
        Console.WriteLine("Method: " + method.Identifier);
}

The followup question is "Why doesn't MemberDeclarationSyntax have an Identifier property?

MemberDeclarationSyntax is the base class for more than just methods and properties. In particular, it's the base class for BaseFieldDeclarationSyntax. Field declarations don't always have a clear identifier.

For example, what should be identifier for the following field be? It has two names.

class Sample
{
    private string fieldOne, fieldTwo;
}

Hopefully this clears it up for you.

arch
var body = member.Body.ToString();

var fullMethodName = member.ToString().Replace(body, "");
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!