This question already has answers here:
How do arrays in C# partially implement IList<T>?
(6个答案)
7年前关闭。
很长一段时间我对以下内容感到好奇:
由于数组实现IList接口(interface),因此允许以下操作:
但:
问题:
数组如何实现
然后,您可以像下面这样使用这些类型:
但这不会编译:
正如JeffN825所指出的,显式实现接口(interface)成员的原因之一是类型不支持它们。例如,
(6个答案)
7年前关闭。
很长一段时间我对以下内容感到好奇:
int[] array = new int[1];
int iArrayLength = array.Length; //1
由于数组实现IList接口(interface),因此允许以下操作:
int iArrayCount = ((IList<int>)array).Count; //still 1
但:
int iArrayCount = array.Count; //Compile error. WHY?
int iArrayLength = array.Length; //This is what we learned at school!
问题:
数组如何实现
IList<T>
(尤其是int Count { get; }
的IList<T>
属性),而又不允许在基类上使用它? 最佳答案
这称为显式接口(interface)成员实现。接口(interface)成员没有公开为该类型的公共(public)成员,但可以通过将引用强制转换为接口(interface)类型来使用。
可以这样在C#中完成:
interface I
{
void M();
}
class C : I
{
public int P { get; set; }
void I.M() { Console.WriteLine("M!"); }
}
然后,您可以像下面这样使用这些类型:
C obj = new C();
obj.P = 3;
((I)obj).M();
但这不会编译:
obj.M();
正如JeffN825所指出的,显式实现接口(interface)成员的原因之一是类型不支持它们。例如,
Add
引发异常(relevant discussion)。实现成员显式的另一个原因是它会复制另一个具有不同名称的公共(public)成员。这就是Count
被明确实现的原因;相应的公共(public)成员是Length.
。最后,一些成员是隐式实现的,即索引器。这两行都起作用(假设arr
是int
的数组):arr[0] = 8;
((IList<int>)arr)[0] = 8;
关于c# - 数组如何在不使用C#实现 “Count”属性的情况下实现IList <T>? [复制],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12461330/