简体   繁体   English

使用点表示法实现C#方法

[英]C# method implementation with dot notation

Reading an article I came across the following C# syntax in method name. 阅读文章我在方法名称中遇到了以下C#语法。

private class sortYearAscendingHelper : IComparer
{
   int IComparer.Compare(object a, object b)
   {
       ...
   }
}

I understand Compare method is method of IComparer interface, but coming from C++ I am not certain what this syntax means. 我理解Compare方法是IComparer接口的方法,但是来自C++我不确定这个语法是什么意思。 If Compare is part of interface, I would expect to mention that only like int Compare(...) . 如果Compare是接口的一部分,我希望只提到int Compare(...) Why we have to specify class? 为什么我们要指定课程?

That is an explicit interface implementation You use it when you derive from multiple interfaces that contain similar (same signature) functions but need different implementations for each interface. 这是一个显式接口实现当您从包含类似(相同签名)函数但需要为每个接口实现不同实现的多个接口派生时,可以使用它。

More information can be found on MSDN . 可以在MSDN上找到更多信息。

(Sample from linked page): (来自链接页面的示例):

If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces. 但是,如果两个接口成员不执行相同的功能,则可能导致一个或两个接口的错误实现。 It is possible to implement an interface member explicitly—creating a class member that is only called through the interface, and is specific to that interface. 可以实现接口成员显式创建仅通过接口调用的类成员,并且特定于该接口。 This is accomplished by naming the class member with the name of the interface and a period. 这是通过使用接口名称和句点命名类成员来完成的。 For example: 例如:

public class SampleClass : IControl, ISurface
{
    void IControl.Paint()
    {
        System.Console.WriteLine("IControl.Paint");
    }
    void ISurface.Paint()
    {
        System.Console.WriteLine("ISurface.Paint");
    }
}

The class member IControl.Paint is only available through the IControl interface, and ISurface.Paint is only available through ISurface. 类成员IControl.Paint只能通过IControl接口使用,而ISurface.Paint只能通过ISurface获得。 Both method implementations are separate, and neither is available directly on the class. 两种方法实现都是分开的,并且都不能直接在类上使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM