我尝试使用Roslyn获取数组值。例如,如果我有这样的C#代码:
int[] arrInt = {10, 20, 30, 40, 50};
然后我如何获得arrInt [0]为10,arrInt [1]为20的信息,依此类推。
答案 0 :(得分:4)
我建议您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的快速监视窗口查看语法树的层次结构。
如果您对代码中的符号应用了一些语义分析,则可能能够获得有关代码中更有意义的信息。