[英]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.