构建语法树
在开始之前,我们需要引入Microsoft.CodeAnalysis.CSharp包
若我们需要编写的代码如下:
using System;
namespace ConsoleApp1;
public class HelloWorld
{
public static void SayHello()
{
Console.WriteLine("Hello, World!");
}
}
创建一个CompilationUnit并添加using语句:
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
var complicationUnit = CompilationUnit()
.AddUsings(
UsingDirective(
IdentifierName("System")));
添加命名空间:
AddMembers(
FileScopedNamespaceDeclaration(
IdentifierName("ConsoleApp1")));
添加HelloWorld类:
AddMembers(
ClassDeclaration("HelloWorld")
.AddModifiers(
Token(SyntaxKind.PublicKeyword))
.AddMembers(/*这里编写SayHello方法*/));
编写SayHello方法:
MethodDeclaration(
PredefinedType(
Token(SyntaxKind.VoidKeyword)),
Identifier("SayHello"))
.WithModifiers(
TokenList(
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.StaticKeyword)))
.WithBody(
Block(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("Console"),
IdentifierName("WriteLine")))
.WithArgumentList(
ArgumentList(
SingletonSeparatedList<ArgumentSyntax>(
Argument(
LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("Hello World")))))))))
构建语法树:
var syntaxTree = SyntaxTree(complicationUnit);
全部代码:
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
var complicationUnit = CompilationUnit()
.AddUsings(
UsingDirective(
IdentifierName("System")))
.AddMembers(
FileScopedNamespaceDeclaration(
IdentifierName("ConsoleApp1")))
.AddMembers(
ClassDeclaration("HelloWorld")
.AddModifiers(
Token(SyntaxKind.PublicKeyword))
.AddMembers(
MethodDeclaration(
PredefinedType(
Token(SyntaxKind.VoidKeyword)),
Identifier("SayHello"))
.WithModifiers(
TokenList(
Token(SyntaxKind.PublicKeyword),
Token(SyntaxKind.StaticKeyword)))
.WithBody(
Block(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("Console"),
IdentifierName("WriteLine")))
.WithArgumentList(
ArgumentList(
SingletonSeparatedList(
Argument(
LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("Hello World")))))))))));
var syntaxTree = SyntaxTree(complicationUnit);