gpt4 book ai didi

c# - 继承 ICollection 的抽象基类

转载 作者:太空狗 更新时间:2023-10-29 21:36:05 26 4
gpt4 key购买 nike

假设我有一个抽象基类 BaseTimeCollection和至少一个具体类ConcreteTimeCollection它继承自基类。

我希望我的基类继承自 ICollection<T> .

继承自 ICollection<T>要求我提供许多方法的实现,包括 IEnumerable.GetEnumerator()IEnumerable<T>.GetEnumerator .

我不想在 BaseTimeCollection 中实现这些方法- 相反,我更愿意在我的每个具体类中单独实现它们。

这就是我遇到麻烦的地方。

GetEnumerator方法需要显式声明,因为其中有两个方法名称相同但返回类型不同。但是,似乎一旦我将签名明确化,我就不能再使用抽象修饰符。基本上我被迫实现 GetEnumerator我的基类中的方法。

public abstract class BaseTimeCollection : ICollection<Time>
{
abstract IEnumerator IEnumerable.GetEnumerator(); // compile error: The modifier 'abstract' is not valid for this item
abstract IEnumerator<Time> IEnumerable<Time>.GetEnumerator(); // compile error: The modifier 'abstract' is not valid for this item
}

public class ConcreteTimeCollection : BaseTimeCollection
{
IEnumerator IEnumerable.GetEnumerator()
{
// this is where I would like to provide my implementation for IEnumerable.GetEnumerator()
}

IEnumerator<Time> IEnumerable<Time>.GetEnumerator()
{
// this is where I would like to provide my implementation for IEnumerable<Time>.GetEnumerator()
}
}
  1. 我错过了什么?

  2. 有什么方法可以推迟 GetEnumerator 的实现吗?具体类的方法?

最佳答案

通过让显式实现调用抽象类中 protected 抽象方法,然后让子类实现这些抽象方法,您可以轻松地将实现推迟到子类:

public abstract class BaseTimeCollection : ICollection<Time>
{
protected abstract IEnumerator IEnumerable_GetEnumerator();
protected abstract IEnumerator<Time> GenericEnumerable_GetEnumerator();

IEnumerator IEnumerable.GetEnumerator()
{
return IEnumerable_GetEnumerator();
}

IEnumerator<Time> IEnumerable<Time>.GetEnumerator()
{
return GenericEnumerable_GetEnumerator();
}
}

对于糟糕的命名方案感到抱歉......这是我一大早能想到的最好的。

关于c# - 继承 ICollection<T> 的抽象基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6860007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com