我是 C# 的新手(6 个月的工作经验),但它看起来与 Java 非常相似,所以我感觉很自在。
但是,今天我尝试实现 IComparer 接口(interface)并想知道为什么它会给我一个错误:
public class AlphabeticalReportSort : IComparer
{
int Compare(Object x, Object y)
{
return 0;
}
}
它似乎需要您将其实现为:
public class AlphabeticalReportSort : IComparer
{
int IComparer.Compare(Object x, Object y)
{
return 0;
}
}
我在接口(interface)声明中没有注意到任何需要这样做的地方,而且在 C# 中似乎通常不需要这样做。
有人知道为什么吗?
最佳答案
Why does IComparer require you to define IComparer.Compare(Object x, Object y) and not just Compare(Object x, Object y)?
事实并非如此。完整的错误信息是:
'AlphabeticalReportSort' does not implement interface member 'IComparer.Compare(object, object)'. 'AlphabeticalReportSort.Compare(object, object)' cannot implement an interface member because it is not public.
注意第二句。您的 int Compare()
方法是私有(private)的,而不是公共(public)的,因此不能充当接口(interface)方法的实现。
int IComparer.Compare()
是一个显式实现,它可以编译,因为显式接口(interface)实现始终是公共(public)的(因为所有接口(interface)成员都是公共(public)的),因此不需要访问修饰符。但就您而言,只需将您的方法标记为 public 就足够了。您很少需要显式实现接口(interface)方法,据我所知,您实际上不能在接口(interface)定义本身中要求它。
关于c# - 为什么 IComparer 要求您定义 IComparer.Compare(Object x, Object y) 而不仅仅是 Compare(Object x, Object y)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40281575/