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
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.
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();
}
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());
}
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;
}
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.