c# - 查找所有父类型(包括基类和接口(interface))

标签 c# .net

我希望能够找到特定类型的所有父类型(基类和接口(interface))。

EG 如果我有

class A : B, C { }
class B : D { }
interface C : E { }
class D { }
interface E { }

我想知道 A B C D and E and Object

最好的方法是什么?有没有一种反射(reflection)方法可以做到这一点,或者我需要自己做点什么。

====编辑====

是这样的吗?

public static IEnumerable<Type> ParentTypes(this Type type)
    {
        foreach (Type i in type.GetInterfaces())
        {
            yield return i;
            foreach (Type t in i.ParentTypes())
            {
                yield return t;
            }
        }

        if (type.BaseType != null)
        {
            yield return type.BaseType;
            foreach (Type b in type.BaseType.ParentTypes())
            {
                yield return b;
            }
        }
    }

我有点希望我不必自己做,但是哦,好吧。

最佳答案

更通用的解决方案:

public static bool InheritsFrom(this Type type, Type baseType)
{
    // null does not have base type
    if (type == null)
    {
        return false;
    }

    // only interface or object can have null base type
    if (baseType == null)
    {
        return type.IsInterface || type == typeof(object);
    }

    // check implemented interfaces
    if (baseType.IsInterface)
    {
        return type.GetInterfaces().Contains(baseType);
    }

    // check all base types
    var currentType = type;
    while (currentType != null)
    {
        if (currentType.BaseType == baseType)
        {
            return true;
        }

        currentType = currentType.BaseType;
    }

    return false;
}

或者实际获取所有父类型:

public static IEnumerable<Type> GetParentTypes(this Type type)
{
    // is there any base type?
    if (type == null)
    {
        yield break;
    }

    // return all implemented or inherited interfaces
    foreach (var i in type.GetInterfaces())
    {
        yield return i;
    }

    // return all inherited types
    var currentBaseType = type.BaseType;
    while (currentBaseType != null)
    {
        yield return currentBaseType;
        currentBaseType= currentBaseType.BaseType;
    }
}

关于c# - 查找所有父类型(包括基类和接口(interface)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8868119/

相关文章:

c# - C#中的对象初始化

c# - 如何打包和部署带有符号和源代码的 NuGet 包,以便调试器可以使用该源代码?

c# - 无法将 azure storage api nuget 包添加到我的控制台应用程序

c# - 如何在代码中向 WPF 窗口添加形状?

.net - 是否有用于读取 RAW 文件的良好 .NET 库?

.net - 如何将数据集/数据表从 Tomcat 中继到 .NET 应用程序?

c# - 根据选定的网格行项目检索隐藏对象属性 C#

c# - C#枚举默认实现了哪些接口(interface)

c# - 使用泛型方法将继承的泛型类添加到字典

.net - 异步 SQL 批量复制和批量选择