如何修复此代码?我例外。此异常是System.InvalidOperationException:'指定的项目不是列表的元素。'
using System;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var tree = SyntaxFactory.ParseExpression("(x + y) * z").SyntaxTree;
var root = (BinaryExpressionSyntax)tree.GetRoot();
foreach (var i in root.DescendantNodes())
{
if (i.Kind() == SyntaxKind.IdentifierName)
{
string str = "64";
var subTree = SyntaxFactory.ParseExpression(str).SyntaxTree;
var subRoot = (LiteralExpressionSyntax)subTree.GetRoot();
var subNode = subRoot.DescendantNodes().OfType<LiteralExpressionSyntax>();
var newRoot = root.ReplaceNode(root.FindNode(i.Span), subNode);
Console.WriteLine(newRoot);
}
}
Console.ReadLine();
}
}
}
我这样解决了这个问题
using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var tree = SyntaxFactory.ParseExpression("(x + y) * z").SyntaxTree;
var root = (BinaryExpressionSyntax)tree.GetRoot();
foreach (var i in root.DescendantNodes())
{
if (i.Kind() == SyntaxKind.IdentifierName)
{
string str = "64";
var subTree = SyntaxFactory.ParseExpression(str).SyntaxTree;
var subRoot = (LiteralExpressionSyntax)subTree.GetRoot();
var newRoot = SyntaxNodeExtensions.ReplaceNode(root, i, subRoot);
Console.WriteLine(newRoot);
}
}
Console.ReadLine();
}
}
}