Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);

            }
        }

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

like image 946
Mark P Neyer Avatar asked Dec 01 '09 02:12

Mark P Neyer


People also ask

What does AC mean in probability?

The complement of an event is the subset of outcomes in the sample space that are not in the event. A complement is itself an event. The complement of an event A is denoted as A c A^c Ac or A′. An event and its complement are mutually exclusive and exhaustive.

What does B given a mean?

The conditional probability of an event B is the probability that the event will occur given the knowledge that an event A has already occurred. This probability is written P(B|A), notation for the probability of B given A.

How do you solve given probability?

Divide the number of events by the number of possible outcomes. After determining the probability event and its corresponding outcomes, divide the total number of ways the event can occur by the total number of possible outcomes.


1 Answers

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());
}
like image 169
SLaks Avatar answered Sep 19 '22 17:09

SLaks