Correct way to check the type of an expression in

2019-04-19 11:20发布

问题:

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.