相关疑难解决方法(0)

为什么通用类型约束不可继承/分层实施

物品类

public class Item
{
    public bool Check(int value) { ... }
}
Run Code Online (Sandbox Code Playgroud)

具有泛型类型约束的基本抽象类

public abstract class ClassBase<TItem>
    where TItem : Item
{
    protected IList<TItem> items;

    public ClassBase(IEnumerable<TItem> items)
    {
        this.items = items.ToList();
    }    

    public abstract bool CheckAll(int value);
}
Run Code Online (Sandbox Code Playgroud)

没有约束的继承类

public class MyClass<TItem> : ClassBase<TItem>
{
    public override bool CheckAll(int value)
    {
        bool result = true;
        foreach(TItem item in this.items)
        {
            if (!item.Check(value)) // this doesn't work
            {
                result = false;
                break;
            }
        }
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道为什么泛型类型约束不可继承?因为如果我的继承类继承自基类并传递其对基类具有约束的泛型类型,则它自动意味着继承类中的泛型类型应具有相同的约束而不显式定义它.不应该吗? …

c# inheritance generic-constraints

26
推荐指数
1
解决办法
5657
查看次数

标签 统计

c# ×1

generic-constraints ×1

inheritance ×1