System.InvalidOperationException:'指定的项目不是列表的元素。'

问题描述 投票:0回答:1

如何修复此代码?我例外。此异常是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();
        }
    }
}
c# .net roslyn
1个回答
0
投票

我这样解决了这个问题

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();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.