[英]How can I access to method parameter's own type data in specific class using Roslyn API(C# Code Analysis)
I'm developing my own custom rules using Roslyn API(C# Code Analysis) . 我正在使用Roslyn API(C#代码分析)开发自己的自定义规则。
I want to get method parameter's own type class inheritance information in specific namespace's name. 我想以特定名称空间的名称获取方法参数自己的类型类继承信息。
First, I initialized RegisterSyntaxNodeAction
to SyntaxKind.CompilationUnit
in DiagnosticAnalyzer class's Initialize method
. 首先,我在
DiagnosticAnalyzer class's Initialize method
SyntaxKind.CompilationUnit
RegisterSyntaxNodeAction
初始化为SyntaxKind.CompilationUnit
。
Second, I accessed specific namespace's name( ex:BIZprj
). 其次,我访问了特定名称空间的名称(
ex:BIZprj
)。
Third, I got the parameter's type instance( ex:parameterType
) 第三,我得到了参数的类型实例(
ex:parameterType
)
Until here, I tried to serveral times to get parameter type instance's inheritance name. 在此之前,我尝试过多次获取参数类型实例的继承名称。 How can I resolve this?
我该如何解决?
my code example 我的代码示例
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.!!**
}
}
}
Try the following code, where I have documented various parts, we are essentially going to the MethodNode
, traversing further to the ParameterSyntax
collection and for each parameter
first node is Type
and Last is the parameter name
, once we have the type of any parameter, we can also get the Base type
and from that you can fetch the Type Name as shown in the image 尝试下面的代码,在这里我已经记录了各个部分,我们实际上是去到
MethodNode
,然后遍历ParameterSyntax
集合,对于每个parameter
第一个节点是Type
,Last是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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.