繁体   English   中英

检查 ClassDeclarationSyntax 是否实现了特定接口(独立代码分析工具)

[英]Check if ClassDeclarationSyntax implements a specific interface (Standalone code analysis tool)

在我的 .NET 6 Standalone Code Analysis Tool中,我有一个Compilation实例、一个SemanticModel实例和一个ClassDeclarationSyntax实例。

我需要知道 class 是否实现了特定接口( MediatR.IRequest<TRequest, TResponse>

我可以使用字符串匹配来做到这一点,但我不喜欢那样,有更好的方法吗?

private static async Task AnalyzeClassAsync(Compilation compilation, SemanticModel model, ClassDeclarationSyntax @class)
{
    var baseTypeModel = compilation.GetSemanticModel(@class.SyntaxTree);

    foreach (var baseType in @class.BaseList.Types)
    {
        SymbolInfo symbolInfo = model.GetSymbolInfo(baseType.Type);
        var originalSymbolDefinition = (INamedTypeSymbol)symbolInfo.Symbol.OriginalDefinition;
        if (!originalSymbolDefinition.IsGenericType)
            return;
        if (originalSymbolDefinition.TypeParameters.Length != 2)
            return;

        if (originalSymbolDefinition.ToDisplayString() != "MediatR.IRequestHandler<TRequest, TResponse>")
            return;

        // Do other stuff here
    }
}

我使用这种扩展方法:

public static class TypeExtensions
{
  public static bool IsAssignableToGenericType(this Type type, Type genericType)
  {
    if (type == null || genericType == null) return false;
    if (type == genericType) return true;
    if (genericType.IsGenericTypeDefinition && type.IsGenericType && type.GetGenericTypeDefinition() == genericType) return true;
    if (type.GetInterfaces().Where(it => it.IsGenericType).Any(it => it.GetGenericTypeDefinition() == genericType)) return true;
    return IsAssignableToGenericType(type.BaseType, genericType);
  }
}

像这样使用它:

var doesIt = typeof(MyClass).IsAssignableToGenericType(typeof(MediatR.IRequestHandler<,>)));

获取对接口的引用,然后检查 class 是否实现它是一种更简洁的方法。

private static async Task AnalyzeClassAsync(Compilation compilation, SemanticModel model, ClassDeclarationSyntax @class)
{
    // MediatR.IRequestHandler`2 should be the fully qualified name
    // `2 indicates that the class/interface takes 2 type parameters
    var targetTypeSymbol = compilation.GetTypeByMetadataName("MediatR.IRequestHandler`2");

    // ...

    var implementsIRequestHandler = originalSymbolDefinition.AllInterfaces.Any(i => i.Equals(targetTypeSymbol))

   // Do other stuff here
}

暂无
暂无

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

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