为什么在声明接口方法时不 "IEnumerator IEnumerator.GetEnumerator()" ? IEnumerable接口
Why not "IEnumerator IEnumerator.GetEnumerator()" while declaring the interface method ? IEnumerable interface
我有 3 个关于 IEnumerable<T>
和 IEnumerator<T>
界面的问题:
为什么不IEnumerator IEnumerator.GetEnumerator()
,因为它是接口方法?
为什么不能public?
为什么返回值 Current 应该是一个对象,即使我知道具体类型?
代码:(题目已标出)
public class myIEnumCollection : IEnumerable<int>
{
public IEnumerator GetEnumerator() // 1)
{
return new myIEnumerator();
}
IEnumerator<int> IEnumerable<int>.GetEnumerator(){ // 2)
throw new NotImplementedException();
}
}
public class myIEnumerator: IEnumerator<int> {
public int Current{get; private set; } = 0;
object IEnumerator.Current => Current; // 3)
public bool MoveNext(){
Current++;
return true;
}
public void Reset() {
Current = 0;
}
public void Dispose(){
}
}
谢谢!
- 我认为你的实现被颠倒了。如果您遵循
IEnumerable<T>
's page 上的示例代码,您将像这样声明它:
public IEnumerator<int> GetEnumerator()
{
return new myIEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerable<T>
implements the non-generic interface IEnumerable
and both define a method GetEnumerable()
with different return types. Because of this, only one of these methods can be directly accessed (see this question for more information: C# Interfaces. Implicit implementation versus Explicit implementation)
- 与2相关,
IEnumerator<T>
implements the non-generic interface IEnumerator
定义为对象
我有 3 个关于 IEnumerable<T>
和 IEnumerator<T>
界面的问题:
为什么不
IEnumerator IEnumerator.GetEnumerator()
,因为它是接口方法?为什么不能public?
为什么返回值 Current 应该是一个对象,即使我知道具体类型?
代码:(题目已标出)
public class myIEnumCollection : IEnumerable<int>
{
public IEnumerator GetEnumerator() // 1)
{
return new myIEnumerator();
}
IEnumerator<int> IEnumerable<int>.GetEnumerator(){ // 2)
throw new NotImplementedException();
}
}
public class myIEnumerator: IEnumerator<int> {
public int Current{get; private set; } = 0;
object IEnumerator.Current => Current; // 3)
public bool MoveNext(){
Current++;
return true;
}
public void Reset() {
Current = 0;
}
public void Dispose(){
}
}
谢谢!
- 我认为你的实现被颠倒了。如果您遵循
IEnumerable<T>
's page 上的示例代码,您将像这样声明它:
public IEnumerator<int> GetEnumerator()
{
return new myIEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerable<T>
implements the non-generic interfaceIEnumerable
and both define a methodGetEnumerable()
with different return types. Because of this, only one of these methods can be directly accessed (see this question for more information: C# Interfaces. Implicit implementation versus Explicit implementation)- 与2相关,
IEnumerator<T>
implements the non-generic interfaceIEnumerator
定义为对象