var syntaxTree = CSharpSyntaxTree.ParseText("int x = 5;"); var compilation = CSharpCompilation.Create("MyAssembly") .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddSyntaxTrees(syntaxTree); var semanticModel = compilation.GetSemanticModel(syntaxTree); var root = syntaxTree.GetRoot(); var localDecl = root.DescendantNodes().OfType().First(); var boundStatement = semanticModel.GetBoundStatement(localDecl); foreach (var child in boundStatement.ChildBoundNodes) { // Do something with child expressions... }
var syntaxTree = CSharpSyntaxTree.ParseText("int x = 5;"); var compilation = CSharpCompilation.Create("MyAssembly") .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddSyntaxTrees(syntaxTree); var semanticModel = compilation.GetSemanticModel(syntaxTree); var root = syntaxTree.GetRoot(); var localDecl = root.DescendantNodes().OfType().First(); var boundStatement = semanticModel.GetBoundStatement(localDecl); var newExpression = SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(10)); var newStatement = boundStatement.WithExpression(newExpression); var newRoot = root.ReplaceNode(localDecl, (StatementSyntax)newStatement.Syntax); // Output the modified code: Console.WriteLine(newRoot.ToFullString());
var syntaxTree = CSharpSyntaxTree.ParseText("int x = 5;"); var compilation = CSharpCompilation.Create("MyAssembly") .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddSyntaxTrees(syntaxTree); var root = syntaxTree.GetCompilationUnitRoot(); var localDecl = root.DescendantNodes().OfTypeIn conclusion, the BoundStatement class in the Microsoft.CodeAnalysis.CSharp package library is a powerful tool for working with C# code at a high level, providing a way to analyze, manipulate, and generate code programmatically.().First(); var semanticModel = compilation.GetSemanticModel(syntaxTree); var boundStatement = semanticModel.GetBoundStatement(localDecl); var generator = SyntaxGenerator.GetGenerator(new AdhocWorkspace(), LanguageNames.CSharp); var newExpression = generator.LiteralExpression(10); var newStatementSyntax = generator.ExpressionStatement(newExpression); var newStatement = semanticModel.GetBoundStatement(newStatementSyntax); var generatedCode = CodeGenerator.GenerateCode(newStatement); Console.WriteLine(generatedCode);