代码之家  ›  专栏  ›  技术社区  ›  Mefhisto1

获取类从中继承并在C中实现的所有类型和接口#

  •  1
  • Mefhisto1  · 技术社区  · 10 年前

    我看到了与我相似的问题:

    How to find all the types in an Assembly that Inherit from a Specific Type C#

    但是,如果我的类也实现了多个接口呢

    class MyClass: MyBaseClass, IMyInterface1, IMyInterface2
    

    我能得到一系列的东西吗 MyClass 工具,而不仅仅是一个接一个?

    5 回复  |  直到 8 年前
        1
  •  4
  •   Guru Stron    10 年前

    对于可以调用的接口 Type.GetInterfaces()

        2
  •  4
  •   xanatos    10 年前

    如果您对所有基本类型和接口感兴趣,可以使用:

    static Type[] BaseTypesAndInterfaces(Type type) 
    {
        var lst = new List<Type>(type.GetInterfaces());
    
        while (type.BaseType != null) 
        {
            lst.Add(type.BaseType);
            type = type.BaseType;
        }
    
        return lst.ToArray();
    }
    

    使用方式如下:

    var x = BaseTypesAndInterfaces(typeof(List<MyClass>));
    

    甚至可以使其基于通用

    static Type[] BaseTypesAndInterfaces<T>() 
    {
        Type type = typeof(T);
    
        var lst = new List<Type>(type.GetInterfaces());
    
        while (type.BaseType != null) 
        {
            lst.Add(type.BaseType);
            type = type.BaseType;
        }
    
        return lst.ToArray();
    }
    

    var x = BaseTypesAndInterfaces<MyClass>();
    

    但它可能没那么有趣(因为通常你会“发现” MyClass 在运行时,因此不能轻易使用泛型方法)

        3
  •  3
  •   Sergey Kalinichenko    10 年前

    如果要将具有基类型的接口组合到单个数组中,可以执行以下操作:

    var t = typeof(MyClass);
    var allYourBase = new[] {t.BaseType}.Concat(t.GetInterfaces()).ToArray();
    

    请注意,数组将包含所有基,包括 System.Object 。这不适用于 System.对象 ,因为其基本类型为 null .

        4
  •  1
  •   Jamiec    10 年前

    您可以使用以下方式一次性完成所有任务:

    var allInheritance = type.GetInterfaces().Union(new[] { type.BaseType});
    

    实时示例: http://rextester.com/QQVFN51007

        5
  •  0
  •   dahall    5 年前

    下面是我使用的扩展方法:

    public static IEnumerable<Type> EnumInheritance(this Type type)
    {
        while (type.BaseType != null)
            yield return type = type.BaseType;
        foreach (var i in type.GetInterfaces())
            yield return i;
    }