给定C#类型,获取其基类和实现的接口

我正在研究C#中的游戏引擎。 我正在研究的课程名为CEntityRegistry ,它的工作是跟踪游戏中CEntity的许多实例。 我的目标是能够使用给定类型查询CEntityRegistry ,并获取该类型的每个CEntity的列表。

因此,我想做的是维护一张地图:

 private IDictionary<Type, HashSet> m_TypeToEntitySet; 

并因此更新注册表:

 private void m_UpdateEntityList() { foreach (CEntity theEntity in m_EntitiesToRemove.dequeueAll()) { foreach (HashSet set in m_TypeToEntitySet.Values) { if (set.Contains(theEntity)) set.Remove(theEntity); } } foreach (CEntity theEntity in m_EntitiesToAdd.dequeueAll()) { Type entityType = theEntity.GetType(); foreach (Type baseClass in entityType.GetAllBaseClassesAndInterfaces()) m_TypeToEntitySet[baseClass].Add(theEntity); } } 

Type.GetAllBaseClassesAndInterfaces的问题是没有函数Type.GetAllBaseClassesAndInterfaces – 我将如何编写它?

Type具有BaseType属性和FindInterfaces方法。

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

实际上,它几乎确实有Type.GetAllBaseClassesAndInterfaces ,但你必须进行两次调用而不是一次。

您可以编写这样的扩展方法:

 public static IEnumerable GetBaseTypes(this Type type) { if(type.BaseType == null) return type.GetInterfaces(); return Enumerable.Repeat(type.BaseType, 1) .Concat(type.GetInterfaces()) .Concat(type.GetInterfaces().SelectMany(GetBaseTypes)) .Concat(type.BaseType.GetBaseTypes()); } 

基于SLaks的更精确答案将是:

 public static IEnumerable GetBaseClassesAndInterfaces(this Type type) { return type.BaseType == typeof(object) ? type.GetInterfaces() : Enumerable .Repeat(type.BaseType, 1) .Concat(type.GetInterfaces()) .Concat(type.BaseType.GetBaseClassesAndInterfaces()) .Distinct(); } 

使用此代码:

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

函数f将接受一个Type并返回其基类型和接口的列表。

希望能帮助到你。