Correct way to check the type of an expression in Roslyn analyzer?

女生的网名这么多〃 提交于 2019-12-10 01:29:02

问题


I'm writing a code analyzer with Roslyn, and I need to check if an ExpressionSyntax is of type Task or Task<T>.

So far I have this:

private static bool IsTask(ExpressionSyntax expression, SyntaxNodeAnalysisContext context)
{
    var type = context.SemanticModel.GetTypeInfo(expression).Type;
    if (type == null)
        return false;
    if (type.Equals(context.SemanticModel.Compilation.GetTypeByMetadataName("System.Threading.Tasks.Task")))
        return true;
    if (type.Equals(context.SemanticModel.Compilation.GetTypeByMetadataName("System.Threading.Tasks.Task`1")))
        return true;
    return false;
}

It works for Task, but not for Task<int> or Task<string>... I could check the name and namespace, but it's impractical because I have to check each "level" of the namespace.

Is there a recommended way to do it?


回答1:


Check whether the type is a generic type, and, if it is, use OriginalDefinition to return the unconstructed generic type.



来源:https://stackoverflow.com/questions/28240167/correct-way-to-check-the-type-of-an-expression-in-roslyn-analyzer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!