gpt4 book ai didi

.net - IEnumerable.GetEnumerator() 和 IEnumerable.GetEnumerator()

转载 作者:行者123 更新时间:2023-12-03 21:33:15 24 4
gpt4 key购买 nike

在 .net 框架中,有一个通用的 IEnumerable<T>继承自非泛型 IEnumerable 的接口(interface),并且他们都有 GetEnumerator()方法。这两者之间的唯一区别GetEnumerator()是返回类型。
现在我有一个类似的设计,但是当我编译代码时,编译器说:

MyInterface<T>.GetItem() '隐藏继承的成员' MyInterface.GetItem() '。如果打算隐藏,请使用 new 关键字。
MyInterface<T>.GetItem()返回具体类型 T,而 MyInterface.GetItem()返回类型 System.Object。

所以我认为如果 BCL 团队的人编译 .net 框架,他们会得到同样的警告。

我认为编译器警告不好,你怎么看?我该如何解决这个问题?我的意思是我想在调用 MyInterface<T>.GetItem() 时获得具体类型 T不仅仅是 System.Object 类型的实例。

提前致谢! :-)

补充:
我说的是接口(interface)本身:IMyInterface 继承自 IMyInterface,它们都有 GetItem() 方法(IMyInterface.GetItem() 返回类型 T,而 IMyInterface.GetItem() 返回类型 System.Object)。问题是,如果 我们的代码只有这两个接口(interface) ,即没有派生的具体类,我们在编译源代码后会遇到编译器警告。

最佳答案

他们不这样做是因为他们将一个版本编译为显式接口(interface)方法实现。它看起来像这样:

public class SomeClassThatIsIEnumerable<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
// return enumerator.
}

IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
}

这种构造的作用是使第一个 GetEnumerator 方法成为默认方法,而另一个 GetEnumerator 方法只有在调用者首先将 SomeClassThatIsIEnumerable 强制转换为 IEnumerator 类型时才能访问,因此它避免了这个问题。

编辑:根据上面的补充,你会想要使用 new 关键字:
public interface IMyInterface
{
object GetObject();
}

public interface IMyInterface<T> : IMyInterface
{
new T GetObject();
}

// implementation:

public class MyClass : IMyInterface<string>
{
public string GetObject()
{
return "howdy!";
}

object IMyInterface.GetObject()
{
return GetObject();
}
}

关于.net - IEnumerable.GetEnumerator() 和 IEnumerable<T>.GetEnumerator(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2442192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com