Aub*_*ron 2 c# overriding interface
假设我有一个如下界面.
interface CardHolder : IEnumerable<Card>
{
/// <summary> ...
void PutCard(Card card);
/// <summary> ...
void PutCards(Card[] card);
/// Some more methods...
}
Run Code Online (Sandbox Code Playgroud)
我实现如下.
public class ArrayCardHolder : CardHolder
{
private Card[] _cards;
private int _size = 0;
public ArrayCardHolder(int capacity)
{
_cards = new Card[capacity];
}
public void PutCard(Card card)
{
if (IsFull())
throw new Exception("This CardHolder is full. Capacity: " + Capacity());
_cards[_size++] = card;
}
public void PutCards(Card[] cards)
{
if (_size + cards.Length > _cards.Length)
throw new Exception("Adding the Cards would exceed this CardHolder its capacity. Capacity: " + Capacity());
for (int index = 0; index < cards.Length; index++)
_cards[_size++] = cards[index];
}
public IEnumerator<Card> GetEnumerator()
{
for (int index = 0; index < _size; index++)
yield return _cards[index];
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
///More methods.
}
Run Code Online (Sandbox Code Playgroud)
为什么我不能override在我的关键字中使用关键字ArrayCardHolder
(例如public void override PutCard(Card card) { ///implementation },表明该方法实现(即覆盖)接口?在这种情况下,项目将拒绝构建.
为什么在覆盖时会起作用ToString()?而在实现时为什么没有工作CompareTo(T t)的IComparable<T>?
我应该用什么呢?我担心界面中的文档不适用于我的实现方法.@Override使用注释时,Java就是这种情况.
SO *_*ood 12
接口的方法没有被覆盖,它们被实现.您对 可以覆盖的抽象/虚拟方法感到困惑.
例:
public interface IFoo
{
void DoA();
}
public abstract class BaseFoo : IFoo
{
public void DoA() { } // *this HAS to be implemented*
public virtual void DoB() { }
}
public abstract class MyFoo : BaseFoo
{
// *this CAN be implemented, which would override the default implementation*
public override void DoB() { }
}
Run Code Online (Sandbox Code Playgroud)
正如其他人所提到的,是基类的ToString一种virtual方法object,这就是你可以覆盖它的原因.
| 归档时间: |
|
| 查看次数: |
13434 次 |
| 最近记录: |