在.net框架中,有一个通用的IEnumerable<T>
继承自非泛型的接口IEnumerable
,并且他们都有一个GetEnumerator()
方法。这两者之间的唯一区别GetEnumerator()
是返回类型。
现在我有类似的设计,但是当我编译代码时,编译器说:
MyInterface<T>.GetItem()
'隐藏继承的成员'MyInterface.GetItem()
'。如果打算隐藏,请使用 new 关键字。
The MyInterface<T>.GetItem()
返回具体类型 T,而MyInterface.GetItem()
返回类型 System.Object。
所以我认为如果 BCL 团队的人编译 .net 框架,他们也会得到同样的警告。
我认为编译器警告不好,你觉得呢?我该如何解决这个问题?我的意思是我想在调用时获得具体类型 TMyInterface<T>.GetItem()
不仅仅是 System.Object 类型的实例。
提前致谢! :-)
补充:我说的是接口本身:IMyInterface继承自IMyInterface,并且它们都有 GetItem() 方法(IMyInterface.GetItem() 返回类型 T,而 IMyInterface.GetItem() 返回类型 System.Object)。问题是,如果我们的代码只有这两个接口,即没有派生具体类,编译源代码后会遇到编译器警告。
他们不这样做,因为他们将一个版本编译为显式接口方法实现。它看起来像这样:
public class SomeClassThatIsIEnumerable<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
// return enumerator.
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
}
这种类型的构造的作用是使第一个 GetEnumerator 方法成为默认方法,而只有调用者首先将 SomeClassThatIsIEnumerable 转换为 IEnumerator 类型时才能访问另一个 GetEnumerator 方法,因此它避免了该问题。
编辑:根据上面的补充,您需要使用 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();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)