C#-Roslyn:SyntaxNode转换为FieldDeclarationSyntax
C#-Roslyn:SyntaxNode is converted to FieldDeclarationSyntax
我有一个字段 SyntaxNode:
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
SyntaxNode root = await CSharpSyntaxTree.ParseText("int i= 0;").GetRootAsync(token);
我看到文档了:
Inheritance->Object->SyntaxNode->
CSharpSyntaxNode->
MemberDeclarationSyntax->BaseFieldDeclarationSyntax->FieldDeclarationSyntax
我有 ClassDeclarationSyntax :
private ClassDeclarationSyntax _classDeclaration;
我想将 SyntaxNode 转换成 FieldDeclarationSyntax,然后添加到 ClassDeclarationSyntax。
我该如何处理?
你可以用这样的东西做你想做的事:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Linq;
VariableDeclarationSyntax variableDeclaration = CSharpSyntaxTree.ParseText("int i= 0;")
.GetRoot()
.DescendantNodes()
.OfType<VariableDeclarationSyntax>()
.Single();
_classDeclaration = _classDeclaration
.WithMembers(
SyntaxFactory.SingletonList<MemberDeclarationSyntax>(
SyntaxFactory.FieldDeclaration(variableDeclaration)));
您首先需要通过解析创建变量声明语法。然后下降根节点以检索它。然后将该节点附加到新的 FieldDeclaration。虽然我很好奇你想在这里做什么。 Microsoft.CodeAnalysis.Editing命名空间下有SyntaxRewriter type if you want help changing the code of a tree. There is also the general codefix infrastucture and SyntaxEditor。
我有一个字段 SyntaxNode:
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
SyntaxNode root = await CSharpSyntaxTree.ParseText("int i= 0;").GetRootAsync(token);
我看到文档了:
Inheritance->Object->SyntaxNode->
CSharpSyntaxNode->
MemberDeclarationSyntax->BaseFieldDeclarationSyntax->FieldDeclarationSyntax
我有 ClassDeclarationSyntax :
private ClassDeclarationSyntax _classDeclaration;
我想将 SyntaxNode 转换成 FieldDeclarationSyntax,然后添加到 ClassDeclarationSyntax。
我该如何处理?
你可以用这样的东西做你想做的事:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Linq;
VariableDeclarationSyntax variableDeclaration = CSharpSyntaxTree.ParseText("int i= 0;")
.GetRoot()
.DescendantNodes()
.OfType<VariableDeclarationSyntax>()
.Single();
_classDeclaration = _classDeclaration
.WithMembers(
SyntaxFactory.SingletonList<MemberDeclarationSyntax>(
SyntaxFactory.FieldDeclaration(variableDeclaration)));
您首先需要通过解析创建变量声明语法。然后下降根节点以检索它。然后将该节点附加到新的 FieldDeclaration。虽然我很好奇你想在这里做什么。 Microsoft.CodeAnalysis.Editing命名空间下有SyntaxRewriter type if you want help changing the code of a tree. There is also the general codefix infrastucture and SyntaxEditor。