如何使用 Roslyn API(C# 代码分析)在特定 class 中访问方法参数自身的类型数据

How can I access to method parameter's own type data in specific class using Roslyn API(C# Code Analysis)

我正在使用 Roslyn API(C# 代码分析).

开发自己的自定义规则

我想在特定命名空间的名称中获取方法参数自身的类型class继承信息。

首先,我在DiagnosticAnalyzer class's Initialize method中将RegisterSyntaxNodeAction初始化为SyntaxKind.CompilationUnit

其次,我访问了特定命名空间的名称(ex:BIZprj)。

第三,我得到了参数的类型实例(ex:parameterType)

到这里为止,我尝试了好几次获取参数类型实例的继承名。 我该如何解决?

我的代码示例

public class SampleAnalyzer : DiagnosticAnalyzer
{

//...
public override void Initialize(AnalysisContext context)
{
            context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.CompilationUnit);
}

private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
            var rootNode = (CompilationUnitSyntax)context.Node;
            ... go to MethodNode
    var methodParameters = methodNode.ParameterList.Parameters;
    foreach(var param in methodParameters)
    {
        var parameterType = param.Type;
        // **Here is what I want to get parameter type's inheritance class name.!!**
    }
  }
}

enter image description here

试试下面的代码,我在其中记录了各个部分,我们基本上是去 MethodNode,进一步遍历到 ParameterSyntax 集合,对于每个 parameter 第一个节点是Type 最后是 parameter name,一旦我们有了任何参数的类型,我们还可以获得 Base type 并且您可以从中获取类型名称,如图所示

// Fetch the CompilationUnitSyntax
var rootNode = (CompilationUnitSyntax)context.Node;

// Filter out the collection of MethodDeclarationSyntax
var methodSyntaxNodes = from methodDeclaration 
                        in rootNode.DescendantNodes().Where(x => x is MethodDeclarationSyntax )
                        select methodDeclaration;

// Traverse through each MethodNode                             
foreach(var methodNode in methodSyntaxNodes)
{
    var mNode = (MethodDeclarationSyntax)methodNode;

    // Traverse through each Parameter Syntax       
    foreach(var parameterSytanx in mNode.ParameterList.Parameters)
    {
        // Get First Token and Fetch the BaseType
        var baseType = parameterSytanx.GetFirstToken().GetType().BaseType;
    }           
}