好吧,这是一个非常基本的问题,但我刚刚遇到了它。考虑下面的类:
public class WindowComparer: IComparer, Generic.IComparer<Window> { }
场景 1:我通常声明的方式。
public int Compare (object x, object y)
{
return (this.Compare((Window) x, (Window) y));
}
public int Compare (Window x, Window y) {...}
场景 2:MSDN 文档通常声明它的方式。
int Collections.IComparer.Compare (object x, object y)
{
// [this.Compare] is not recognized. How to access this?
return (this.Compare((Window) x, (Window) y));
}
int Generic.IComparer<Window>.Compare (Window x, Window y) {...}
但是,在尝试方案 2 时,智能感知会丢失 Compare 方法,并且编译器会引发错误,指出 Compare 方法不是 WindowComparer 的成员。我错过了什么?
最佳答案
在第二个场景中是接口(interface) IComparer
和IComparer<Window>
显式实现,以便仅当您将实例分配给 IComparer<Window>
类型的变量时才能访问或调用这些方法。或IComparer
.
WindowComparer comparer = new WindowComparer();
IComparer<Window> windowComparer = comparer;
// call methods of IComparer<Window> on windowComparer
IComparer normalComparer = comparer;
// call methods of IComparer on normalComparer
显式实现接口(interface)是为了保持类的公共(public)接口(interface)清晰,并隐藏基础设施接口(interface)的比较、相等等方法。
关于c# - C# 中的接口(interface)实现语法选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17038573/