whuanles
whuanles

Reputation: 15

C#-Roslyn:Why the code conversion of the string to MethodDeclarationSyntax presents an exception

My code:

stringBuilder.AppendLine("}");
MethodDeclarationSyntax methodDeclaration = default;
var tmp = CSharpSyntaxTree.ParseText(stringBuilder.ToString())
                          .GetRoot()
                          .DescendantNodes();


var list = tmp.OfType<MemberDeclarationSyntax>();

foreach (var item in list)
{
    Console.WriteLine(item.NormalizeWhitespace().ToFullString());

    methodDeclaration = item as MethodDeclarationSyntax;

    if (methodDeclaration != null)
        break;
}
if (methodDeclaration is null)
    throw new Exception("No create Roslyn ...");
return methodDeclaration;

Code

string output there should be no problem:

public void T1()
{
    Console.WriteLine("666");
}

But cannot convert to MethodDeclarationSyntax,how can I solve this problem?

Upvotes: 0

Views: 415

Answers (1)

FlashOver
FlashOver

Reputation: 2073

I am afraid I may misunderstand what you are trying to achieve: Reading your code I assume that you want to find the first method declared in a given SourceText.

The SourceText you are providing does not contain a MethodDeclarationSyntax!

The CSharp code

public void T1()
{
    Console.WriteLine("666");
}

is a GlobalStatementSyntax, containing a LocalFunctionStatementSyntax.

In order for T1 to become a MethodDeclarationSyntax, you want to put it into a Type such as a class, a struct, or an interface:

class C
{
    public void T1()
    {
        Console.WriteLine("666");
    }
}

However, your program now prints both the entire Class and the contained Method to the console before it terminates the loop, because both SyntaxNodes are of type MemberDeclarationSyntax:

  • void T1() is of type MethodDeclarationSyntax that you expect
  • class C is of type ClassDeclarationSyntax, which derives from MemberDeclarationSyntax because it could be nested in another class

I see that you are using Visual Studio. What helped me a lot while learning Roslyn and the CSharpSyntaxTree was (and still is) the Syntax Visualizer.

Upvotes: 3

Related Questions