Given a C# Type, Get its Base Classes and Implemented Interfaces

前端 未结 5 619
庸人自扰
庸人自扰 2020-12-10 16:48

I\'m working on a game engine in C#. The class I\'m working on is called CEntityRegistry, and its job is to keep track of the many instances of CEntity

相关标签:
5条回答
  • 2020-12-10 17:27

    Use this code:

    Func<Type, List<Type>> f = ty =>
    {
        var tysReturn = new List<Type>();
        if (ty.BaseType != null)
        {
            tysReturn.Add(ty.BaseType);
        }
        tysReturn.AddRange(ty.GetInterfaces());
        return tysReturn;
    };
    

    The function f will take a Type and return a list of its base type plus interfaces.

    Hope it helps.

    0 讨论(0)
  • 2020-12-10 17:37

    More refined answer based on one from SLaks would be:

    public static IEnumerable<Type> GetBaseClassesAndInterfaces(this Type type)
    {
        return type.BaseType == typeof(object) 
            ? type.GetInterfaces()
            : Enumerable
                .Repeat(type.BaseType, 1)
                .Concat(type.GetInterfaces())
                .Concat(type.BaseType.GetBaseClassesAndInterfaces())
                .Distinct();
    }
    
    0 讨论(0)
  • 2020-12-10 17:38

    You could write an extension method like this:

    public static IEnumerable<Type> GetBaseTypes(this Type type) {
        if(type.BaseType == null) return type.GetInterfaces();
    
        return Enumerable.Repeat(type.BaseType, 1)
                         .Concat(type.GetInterfaces())
                         .Concat(type.GetInterfaces().SelectMany<Type, Type>(GetBaseTypes))
                         .Concat(type.BaseType.GetBaseTypes());
    }
    
    0 讨论(0)
  • 2020-12-10 17:41

    Here. The previous answers have problems. Also, this answer doesn't need "Distinct". The values are already distinct. And this one is more efficient.

        public static IEnumerable<Type> GetBaseTypes(this Type type, bool bIncludeInterfaces = false)
        {
            if (type == null)
                yield break;
    
            for (var nextType = type.BaseType; nextType != null; nextType = nextType.BaseType)
                yield return nextType;
    
            if (!bIncludeInterfaces)
                yield break;
    
            foreach (var i in type.GetInterfaces())
                yield return i;
        }
    
    0 讨论(0)
  • 2020-12-10 17:51

    Type has a property BaseType and a method FindInterfaces.

    https://msdn.microsoft.com/en-us/library/system.type.aspx

    So actually, it almost does have Type.GetAllBaseClassesAndInterfaces, but you have to make two calls instead of one.

    0 讨论(0)
提交回复
热议问题