为什么 IComparer 要求您定义 IComparer.Compare(Object x, Object y) 而不仅仅是 Compare(Object x, Object y)?

Why does IComparer require you to define IComparer.Compare(Object x, Object y) and not just Compare(Object x, Object y)?

我是 C# 的新手(6 个月的工作经验),但它看起来与 Java 非常相似,所以我感觉很自在。

然而,今天我尝试实现 IComparer 接口并想知道为什么它给我一个错误:

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;
    }
}

我在接口声明中没有注意到任何需要这样做的地方,而且在 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() 方法是私有的,而不是 public,因此不能作为接口方法的实现。

int IComparer.Compare() 是一个显式实现,它可以编译,因为显式接口实现总是 public(因为所有接口成员都是 public),因此不需要访问修饰符。但就您而言,只需标记您的方法 public 就足够了。您很少需要显式实现接口方法,据我所知,您实际上不能在接口定义本身中要求它。