我可以保存同一后代的对象类型的List <>吗?

Ody*_*dys 5 c# oop inheritance list

我需要保存允许执行某些操作的对象类型列表.

实施例Animal有3个后代Tiger,Human,Hippo

我想只允许Tigers和Hippos被关在动物园的笼子里?我需要一份动物类型清单.

我会喜欢比这更好的东西 List<Type>

这只是一个简化的例子.我不喜欢笼子里的动物..

编辑

既然不清楚.我想在列表中保存对象类型而不是实际对象.

例:

List<Type> types = new List<Type>();
types.Add(typeof(Hippo));
types.Add(typeof(Tiger));
Run Code Online (Sandbox Code Playgroud)

这是程序员可以做的限制,types.Add(typeof(Human))这是我不想要的.

EDIT2

只是为了澄清我的问题.我希望能够动态地Register允许类型,而不是if因为一些答案.

Ada*_*rth 4

如果您想要仅包含某些类型的列表:

泛型中没有任何东西可以支持您所要求的内容,因此只需创建一个自定义类型,该自定义类型允许您存储Type类型并在运行时具有代码以防止无效条目:

public class CagedTypes 
{
    private readonly List<Type> _types;

    public void Add(Type t)
    {
        if (t == typeof(Hippo) || t == typeof(Tiger))
            _types.Add(t);
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然我不明白为什么你可能需要这个。

如果您想要仅包含某些类型的列表,则可以选择:

执行与上面相同的操作,但包含下面的接口并将添加检查更改为:

public void Add(Type t)
{
    if (t.GetInterfaces().Contains(typeof(ICanBeHeldInZooCage)))
        _types.Add(t);
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用属性,因为您可以使用该方法查询类型的任何属性GetAttributes

如果您只想在列表中包含某些实例:

创建标记接口:

public interface ICanBeHeldInZooCage
Run Code Online (Sandbox Code Playgroud)

然后Tiger实施Hippo(不需要做任何事情),然后你可以:

var cagedAnimals = new List<ICanBeHeldInZooCage>();
Run Code Online (Sandbox Code Playgroud)