簡體   English   中英

將System.Type列表約束為從基本類型繼承的類型

[英]Constrain a list of System.Type to types that inherit from a base type

如果我有代碼:

List<Type> Requires = new List<Type>();

我將如何限制此列表中的類型,使其具有共同的父代?

例如:

List<Type : Component> Requires = new List<Type>()

編輯:多一點背景,所以也許人們可以理解為什么我需要這個。 我有一個類Entity ,它包含的列表Components 每個組件都需要有一個作為依賴項列表的Component類型列表。 因此,在運行時,當您嘗試將Component添加到Entity ,它將進行快速檢查以查看該Entity是否已連接了必需的組件。

例:

//Entity.cs
//...
_components = new List<Component>();
//...
public T AddComponent<T>() where T : Component, new()
{
    var temp = new T();
    if (_components.Exists((x) => x is T)) return null;
    foreach (var t in temp.Requires)
    {
        if (_components.Exists(x => x.GetType() == t)) return null;
    }
    _components.Add(new T());
    temp.gameObject = this;
    return temp;
}
//...

//Component.cs
//...
protected internal Entity gameObject;
protected internal List<Type> Requires { get; }
//...

經過大量的工作,我找到了解決自己問題的方法。

//Component.cs
public abstract class Component {
    //...
    protected internal Entity gameObject;
    private RequiresList _requires;
    //...
    protected internal RequiresList Requires
    {
        get => _requires;
        private set => _requires = (RequiresList)value.FindAll(x => x.IsSubclassOf(typeof(Component)));
    }
    //...
    public class RequiresList : List<Type>
    {
        public RequiresList() { }
        public RequiresList(IEnumerable<Type> types) : base(types) { }
        public RequiresList(int capacity) : base(capacity) { }

        public new Type this[int index]
        {
            get => base[index];
            set
            {
                if (isComp(value))
                    base[index] = value;
            }
        }

        public new void Add(Type type)
        {
            if (isComp(type))
                base.Add(type);
        }

        private static bool isComp(Type type)
        {
            return type.IsSubclassOf(typeof(Component));
        }
    }
    //...
}

//Entity.cs
public abstract class Entity {
    //...
    _components = new List<Component>();
    //...
    public T AddComponent<T>() where T : Component, new()
    {
        var temp = new T();
        if (_components.Exists((x) => x is T)) return null;
        foreach (var t in temp.Requires)
        {
            if (_components.Exists(x => x.GetType() == t)) return null;
        }
        _components.Add(new T());
        temp.gameObject = this;
        return temp;
    }
    //...
}

我創建了一個新的存儲類型調用RequiresList ,它檢查插入其中的所有System.Type ,以查看它們是否是Component的子類。 我還確保,如果有人嘗試用一個全新的列表替換列表,它將刪除新列表中不是Component的所有索引。

暫無
暫無

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

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