简体   繁体   English

C# - 子类类型列表

[英]C# - list of subclass Types

I'd like to have a List of Class Types (not a list of Class instances) where each member of the List is a Subclass of MyClass. 我想要一个类类型列表(不是类实例列表),其中List的每个成员都是MyClass的子类。

For example, i can do this: 例如,我可以这样做:

List<System.Type> myList;
myList.Add(typeof(mySubClass));

but i'd like to restrict the list to only accept subclasses of MyClass. 但我想限制列表只接受MyClass的子类。

This is distinct from questions like this . 与此类问题截然不同。 Ideally i'd like to avoid linq, as it's currently unused in my project. 理想情况下,我想避免linq,因为它在我的项目中目前尚未使用。

Servy is right in his comment , and Lee in his : it's much more preferable to compose than inherit . Servy在他的评论中是正确的Lee 在他的评论 组合比继承更为可取 So this is a good option: 所以这是一个很好的选择:

public class ListOfTypes<T>
{
    private List<Type> _types = new List<Type>();
    public void Add<U>() where U : T
    {
        _types.Add(typeof(U));
    }
}

Usage: 用法:

var x = new ListOfTypes<SuperClass>();
x.Add<MySubClass>()

Note that you can make this class implement an interface like IReadOnlyList<Type> if you want to give other code read access to the contained Type s without other code having to depend on this class. 请注意,如果要为其他代码提供对包含的Type的读访问权,而不需要依赖此类的其他代码,则可以使此类实现类似IReadOnlyList<Type>的接口。

But if you want to inherit anyway, you could create your own class that inherits from List , then add your own generic Add method like this: 但是如果你想继承,你可以创建自己继承自List的类,然后添加你自己的通用Add方法,如下所示:

public class ListOfTypes<T> : List<Type>
{
    public void Add<U>() where U : T
    {
        Add(typeof(U));
    }
}

Just be aware of what Lee said : with this second version you can still Add(typeof(Foo)) . 只要知道Lee说的话 :用第二个版本你仍然可以Add(typeof(Foo))

You should derive a list class from List and override the Add method to perform the type checking that you need. 您应该从List派生一个列表类,并覆盖Add方法以执行您需要的类型检查。 I'm not aware of a way in .NET to do that automatically. 我不知道在.NET中自动执行此操作的方法。

Something like this could work: 像这样的东西可以工作:

public class SubTypeList : List<System.Type>
{
    public System.Type BaseType { get; set; }

    public SubTypeList()
        : this(typeof(System.Object))
    {
    }

    public SubTypeList(System.Type baseType)
    {
        BaseType = BaseType;
    }

    public new void Add(System.Type item)
    {
        if (item.IsSubclassOf(BaseType) == true)
        {
            base.Add(item);
        }
        else
        {
            // handle error condition where it's not a subtype... perhaps throw an exception if
        }
    }
}

You would need to update the other methods that add/update items to the list (index setter, AddRange, Insert, etc) 您需要更新向列表添加/更新项的其他方法(索引setter,AddRange,Insert等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM