鉴于C#类型,获取它的基类和实现的接口 [英] Given a C# Type, Get its Base Classes and Implemented Interfaces

查看:348
本文介绍了鉴于C#类型,获取它的基类和实现的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作在C#中的游戏引擎。我工作的类名为 CEntityRegistry ,它的任务是保持 CEntity 的许多情况跟踪在游戏里。我的目标是能够查询 CEntityRegistry 与给定类型,并获得每个 CEntity 的一个列表类型。

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 in the game. My goal is to be able to query the CEntityRegistry with a given type, and get a list of each CEntity of that type.

我想要做什么,因此,是保持一个图:

What I'd like to do, therefore, is maintain a map:

private IDictionary<Type, HashSet<CEntity>> m_TypeToEntitySet;

和更新正是如此注册表:

And update the registry thusly:

private void m_UpdateEntityList()
        {
            foreach (CEntity theEntity in m_EntitiesToRemove.dequeueAll())
            {
                foreach (HashSet<CEntity> 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 - ?我怎么会去写它

The problem I have is that there is no function Type.GetAllBaseClassesAndInterfaces- How would I go about writing it?

推荐答案

类型有一个属性基本类型和方法FindInterfaces。

Type has a property BaseType and a method FindInterfaces.

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

因此,实际上,它几乎确实有 Type.GetAllBaseClassesAndInterfaces ,但你必须做出两次调用,而不是一个。

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

这篇关于鉴于C#类型,获取它的基类和实现的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆