【问题标题】:Get all concrete implementations of a generic interface获取通用接口的所有具体实现
【发布时间】:2016-12-02 22:16:24
【问题描述】:

我在问题的第一部分找到了这个answer。然而,它也在我的收藏中返回接口。

我正在尝试获取接口的所有具体实现

public interface IPermissionAccessDetails<T,TZ>
{
    List<PermissionAccessDetails<T,TZ>> AccessDetails { get; }
}

这是唯一的具体实现(到目前为止):

    public class BillingPermissionAccessDetails : IPermissionAccessDetails<BillingPermission, EBilling>
    {
        public List<PermissionAccessDetails<BillingPermission, EBilling>> AccessDetails => Config();
    }

这是我用来从上面引用的答案中查找所有实现(几乎是逐字记录)的代码。

 public static List<Type> GetImplementations(Type desiredType)
    {
        return Assembly.GetExecutingAssembly().GetTypes()
                    .Where(type => DoesTypeSupportInterface(type, desiredType)).ToList();
    }

    static bool DoesTypeSupportInterface(Type type, Type inter)
    {
        if (inter.IsAssignableFrom(type))
            return true;
        if (type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == inter))
            return true;
        return false;
    }


var allPermissionAccessTypeDetails = HelperMethods.GetImplementations(typeof(IPermissionAccessDetails<,>));

我的问题是 allPermissionAccessTypeDetails 在集合中应该只有 1 项 - 但它也包括 IPermissionAccessDetails 类型。我该如何排除?

【问题讨论】:

    标签: generics c#-4.0 reflection


    【解决方案1】:

    找到了。修改了辅助方法:

            static bool DoesTypeSupportInterface(Type type, Type inter)
        {
            if (type.IsInterface)
                return false;
            if (inter.IsAssignableFrom(type))
                return true;
            if (type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == inter))
                return true;
            return false;
        }
    

    【讨论】:

      猜你喜欢
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      • 2010-09-06
      • 1970-01-01
      相关资源
      最近更新 更多