我决定使用 IEnumerable 接口。我为数组创建了自己的类并实现了 GetEnumerator 方法。但是为什么第27行没有public会出现错误呢?此外,我在某处读到,相反,在实现接口时,不能编写 public 。
using System;
using System.Collections;
class Interfaces
{
public class IntArray: IEnumerable
{
private int[] a;
public IntArray(int n)
{
a = new int[n];
}
public int this[int i]
{
get
{
return a[i];
}
set
{
a[i] = value;
}
}
public IEnumerator GetEnumerator() // Почему без public ошибка?
{
for (int i = 0; i < a.Length; i++)
yield return a[i];
}
}
static void Main()
{
IntArray x = new IntArray(10);
for (int i = 0; i < 10; i++)
x[i] = 2 * i;
foreach (var t in x) Console.Write(t + " ");
Console.WriteLine();
}
}
你误读了。接口是公共协议,公共总是使用它来与公共行为交互,因为接口是行为的公共协议。(嗯,也就是说,它是对抽象行为的预期。)
附加信息
维基百科
哈布拉哈布尔