簡體   English   中英

給定C#類型,獲取其基類和實現的接口

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

我正在研究C#中的游戲引擎。 我正在研究的課程名為CEntityRegistry ,它的工作是跟蹤游戲中CEntity的許多實例。 我的目標是能夠使用給定類型查詢CEntityRegistry ,並獲取該類型的每個CEntity的列表。

因此,我想做的是維護一張地圖:

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

並因此更新注冊表:

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的問題是沒有函數Type.GetAllBaseClassesAndInterfaces - 我將如何編寫它?

您可以編寫這樣的擴展方法:

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

Type具有BaseType屬性和FindInterfaces方法。

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

實際上,它幾乎確實有Type.GetAllBaseClassesAndInterfaces ,但你必須進行兩次調用而不是一次。

基於SLaks的更精確答案將是:

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

這里。 以前的答案有問題。 此外,這個答案不需要“區別”。 價值已經不同了。 這個更有效率。

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

使用此代碼:

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

函數f將采用Type並返回其基類型和接口的列表。

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM