简体   繁体   English

如何使用Roslyn从对象实例化获取类标识符

[英]How to get the class identifier from object instantiation using Roslyn

I'm trying to create an analyzer that will find where each method invocation comes from especially the class where the method is defined. 我正在尝试创建一个分析器,该分析器将查找每个方法调用的来源,尤其是方法定义的类。

let's assume we have the following code: 假设我们有以下代码:

 Movie myMovie = new Movie();
 myMovie.Rent();

my analyzer till now can return the expression myMovie.Rent() as ExpressionSyntax 我的分析器到目前为止可以将表达式myMovie.Rent()作为ExpressionSyntax

What exactly I want, is where the analyzer found a method invocation using an object in this case myMovie.Rent() , returns the class where the method is defined and the object is instantiated in this case is Movie . 我要的就是分析器在这种情况下使用对象myMovie.Rent()找到一个方法调用的地方,返回定义方法的类,在这种情况下实例化的对象是Movie

I'm blocked that why I didn't write any code for it if you have any idea or code example, I appreciate it. 我很抱歉,如果您有任何想法或代码示例,为什么不为它编写任何代码,我对此表示赞赏。

First of all, in your analyzer class, inside the Initialize method you should register the syntax node action : 首先,在分析器类的Initialize方法内部,应注册语法节点action

public override void Initialize(AnalysisContext context)
{
    context.RegisterSyntaxNodeAction(SyntaxNodeAnalyze, SyntaxKind.InvocationExpression);
}

In this method, we registered SyntaxNodeAnalyze method to get callbacks from the analyzer. 在此方法中,我们注册了SyntaxNodeAnalyze方法以从分析器获取回调。 Inside this method, by using the 'SyntaxNodeAnalysisContext' we can query information about the semantic objects . 在此方法内部,通过使用“ SyntaxNodeAnalysisContext”,我们可以查询有关semantic objects In the following sample, I used SemanticModel to be able to enumerate the custom attributes that I was declared and now, I used them above the method declaration. 在以下示例中,我使用SemanticModel来枚举已声明的自定义属性,现在,在方法声明上方使用了它们。

private static void SyntaxNodeAnalyze(SyntaxNodeAnalysisContext context)
{
    SemanticModel semanticModel = context.SemanticModel;
    InvocationExpressionSyntax method = (InvocationExpressionSyntax)context.Node;

    var info = semanticModel.GetSymbolInfo(method).Symbol;
    if (info == null)
         return new List<AttributeData>();

    var attribs = info.GetAttributes().Where(f => f.AttributeClass.MetadataName.Equals(typeof(ThrowsExceptionAttribute).Name));

    foreach (var attrib in attribs)
    {
        ...
    }            
}

As you can see in the above code, we can gather useful information by using the GetSymbolInfo method of the 'SemanticModel'. 如您在上面的代码中看到的,我们可以使用'SemanticModel'的GetSymbolInfo方法收集有用的信息。 You can use this method to get information about Methods , Properties and other semantic objects. 您可以使用此方法来获取有关MethodsProperties和其他语义对象的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM