【问题标题】:C# - list of subclass TypesC# - 子类类型列表
【发布时间】:2017-03-22 17:33:15
【问题描述】:

我想要一个类类型列表(不是类实例列表),其中列表的每个成员都是 MyClass 的子类。

例如,我可以这样做:

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

但我想限制列表只接受 MyClass 的子类。

这与问题like this 不同。 理想情况下,我想避免使用 linq,因为它目前在我的项目中未使用。

【问题讨论】:

  • 创建您自己的列表,继承自 List 并覆盖 Add 方法。
  • 我认为您无法在编译时验证这一点。您可以创建自己的列表并添加添加。
  • @dcg 这根本不允许您完成此操作,因为Add 不是虚拟的。您需要编写一个列表,而不是从它继承。

标签: c# list class generics types


【解决方案1】:

Servy is right in his comment,和Lee in hisit's much more preferable to compose than inherit。所以这是一个不错的选择:

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

用法:

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

请注意,如果您想授予其他代码对包含的Types 的读取访问权限,而无需其他代码依赖于此类,则可以使此类实现类似IReadOnlyList&lt;Type&gt; 的接口。

但如果你想继承,你可以创建你自己的继承自List的类,然后像这样添加你自己的通用Add方法:

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

请注意what Lee said:使用第二个版本,您仍然可以Add(typeof(Foo))

【讨论】:

  • 我会避免继承,因为你也可以这样做Add(typeof(string))
【解决方案2】:

您应该从 List 派生一个列表类并重写 Add 方法以执行您需要的类型检查。我不知道 .NET 中有一种方法可以自动执行此操作。

这样的事情可能会起作用:

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

您需要更新将项目添加/更新到列表的其他方法(索引设置器、AddRange、Insert 等)

【讨论】:

    猜你喜欢
    • 2017-01-28
    • 2014-11-27
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 2015-12-12
    • 2023-03-06
    • 2012-05-29
    • 2014-02-07
    相关资源
    最近更新 更多