【问题标题】:Why don't array types have Add() method although they implement IList<T>?为什么数组类型虽然实现了 IList<T>,却没有 Add() 方法?
【发布时间】:2019-02-03 21:30:27
【问题描述】:

int[]等数组类型实现了很多接口,IList就是其中之一。 IList 需要实现 Add(T) 方法(因为 IList 继承自 ICollection)。

我正在编写一个“CircularArray”类,它本身包含一个数组,但由于是循环的,因此没有任何索引超出范围异常。 类的定义是这样的:

public class CircularArray<T> : ICloneable, IList<T>, IStructuralComparable, IStructuralEquatable

它应该实现数组所做的所有接口,所以我必须实现 Add 方法。但是……数组没有这个方法,虽然它们实现了“ICollection”接口。

如何为数组完成这一切,以便它们可以实现 ICollection 接口而没有 Add 方法?我想为我的 CircularArray 类做同样的事情。

【问题讨论】:

标签: arrays .net interface icollection


【解决方案1】:

解释在丹尼尔在另一个主题中的回答中。要做你想要实现的就是使用显式接口实现。

    interface ILeft
    {
        int P { get;}
    }   
    class Middle : ILeft
    {
        int ILeft.P { get { return 0; } }
    }

var mid= new Middle();
var abc = mid.P // invalid;
var abc2 = (mid as ILeft).P; //valid

【讨论】:

  • 谢谢!我不知道我可以将实现方法设为私有,我昨天看到并感到震惊,因为我一直认为它们必须是公开的......现在我明白了:D
猜你喜欢
  • 1970-01-01
  • 2016-11-02
  • 2011-08-23
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多