C 中分析儀的內省分析

  1. 建立新的控制檯應用程式
  2. 新增 NuGetMicrosoft.CodeAnalysis
  3. 匯入名稱空間 Microsoft.CodeAnalysis.MSBuildSystem.LinqMicrosoft.CodeAnalysis.CSharp.Syntax
  4. Main 方法中編寫以下示例程式碼:
// Declaring a variable with the current project file path.
const string projectPath = @"C:\<your path to the project\<project file name>.csproj";

// Creating a build workspace.
var workspace = MSBuildWorkspace.Create();
        
// Opening this project.
var project = workspace.OpenProjectAsync(projectPath).Result;

// Getting the compilation.
var compilation = project.GetCompilationAsync().Result;

// As this is a simple single file program, the first syntax tree will be the current file.
var syntaxTree = compilation.SyntaxTrees.First();

// Getting the root node of the file.
var rootSyntaxNode = syntaxTree.GetRootAsync().Result;

// Finding all the local variable declarations in this file and picking the first one.
var firstLocalVariablesDeclaration = rootSyntaxNode.DescendantNodesAndSelf().OfType<LocalDeclarationStatementSyntax>().First();

// Getting the first declared variable in the declaration syntax.
var firstVariable = firstLocalVariablesDeclaration.Declaration.Variables.First();

// Getting the text of the initialized value.
var variableInitializer = firstVariable.Initializer.Value.GetFirstToken().ValueText;

// This will print to screen the value assigned to the projectPath variable.
Console.WriteLine(variableInitializer);

Console.ReadKey();

執行專案時,你將看到在頂部宣告的變數列印到螢幕上。這意味著你成功地自我分析了一個專案並在其中找到了一個變數。