سؤال

Is there any way to extract all variable names from C# code, i.e. a function which takes a source code file and returns an array of variable names in that source code?

هل كانت مفيدة؟

المحلول

A preview version of Microsoft Roslyn was recently released that should make this relatively trivial, since variable names do not require complex type resolving; no context is required outside of the single code file.

Here is a sample implementation; I didn't look into it far enough to validate if all cases of variable declarations are matched, but parameters, fields, local variables and lambda parameters are included. It depends on what you define to be variable names. e.g. you might want to include type parameter names as well?

string sourceCode = "class A { " +
                "int field; " +
                "void B(string parameter) { " +
                "int a, b; int c; " +
                "Action<string> q = (x) => { Console.WriteLine(x); }; " +
                "}";

//or parsefile etc
var syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);

string[] identifierNames = syntaxTree.GetRoot().DescendantNodes()
            .OfType<VariableDeclaratorSyntax>().Select(v => v.Identifier.Text)
            .Concat(syntaxTree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().Select(p => p.Identifier.Text))
            .ToArray();
//identifierNames contains "field", "a", "b", "c", "q", "parameter", "x"

To make this work, Roslyn needs to be included (use Nuget):

PM> Install-Package Microsoft.CodeAnalysis -Pre
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top