gpt4 book ai didi

c# - Roslyn:获取数组值

转载 作者:行者123 更新时间:2023-12-02 22:18:36 26 4
gpt4 key购买 nike

我尝试使用 Roslyn 获取数组值。例如,如果我有这样的 C# 代码:

int[] arrInt = {10, 20, 30, 40, 50};

那我怎么才能得到arrInt[0]是10,arrInt[1]是20,等等。

最佳答案

我鼓励你 check the documentation , FAQ and samples ,尤其是语法和语义分析部分。

解决方法如下:

static void Main(string[] args)
{
string code = "int[] arrInt = {10, 20, 30, 40, 50};";

//Parse Syntax tree
var tree = Roslyn.Compilers.CSharp.SyntaxTree.ParseText(code);

//Locate the arrInt identifier in the Syntax tree
var declarator = tree.GetRoot().DescendantNodesAndSelf().Where(t => t.Kind == Roslyn.Compilers.CSharp.SyntaxKind.VariableDeclarator
&& ((Roslyn.Compilers.CSharp.VariableDeclaratorSyntax)t).Identifier.ValueText == "arrInt").First() as Roslyn.Compilers.CSharp.VariableDeclaratorSyntax;

var index = 1;
var expression = GetExpressionAtInitializer(declarator, index);

Console.WriteLine(expression);

//Examine 'expression' for more information on value at the second index
}

private static Roslyn.Compilers.CSharp.ExpressionSyntax GetExpressionAtInitializer(Roslyn.Compilers.CSharp.VariableDeclaratorSyntax declarator, int index)
{
var initializerExpression = declarator.Initializer.Value as Roslyn.Compilers.CSharp.InitializerExpressionSyntax;
var expression = initializerExpression.Expressions[index];
return expression;
}

可以使用VS的quick watch window来查看语法树的层级。

如果您对代码应用一些语义分析,您可能能够获得有关代码中符号的更有意义的信息。

关于c# - Roslyn:获取数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14099170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com