简体   繁体   English

接口的隐式和显式实现

[英]Implicit and Explicit implementation of interface

While working on a upgrade i happened to come across a code like this. 在进行升级时,碰巧碰到了这样的代码。

interface ICustomization
    {
        IMMColumnsDefinition GetColumnsDefinition();
    }

    class Customization : ICustomization
    {
        private readonly ColumnDefinition _columnDefinition;

        //More code here.

        public ColumnsDefinition GetColumnsDefinition()
        {
            return _columnDefinition;
        }

        ColumnsDefinition ICustomization.GetColumnsDefinition()  //redundant
        {
            return GetColumnsDefinition();            
        }
    }

My question is: Is there any need/use of 'explicit' implementation of interface in this piece of code? 我的问题是:在这段代码中是否需要/使用“显式”接口实现? Will it create any problem if i remove the method (explicit implementation of interface) that i have marked "redundant" above? 如果我删除上面标记为“冗余”的方法(显式实现接口)会不会产生任何问题?

PS: I understand that explicit implementation of interface is very important, and it can be used when we need to give access to a method at interface level only, and to use two interface with same signature of method. PS:我理解接口的显式实现非常重要,当我们需要仅在接口级别访问方法时,可以使用它,并且使用具有相同签名方法的两个接口。

Yup. 对。 Looks redundant. 看起来多余。

Calling it via a Customization type of reference and an ICustomization type of reference results in the same behavior. 通过自定义类型的引用和ICustomization类型的引用调用它会导致相同的行为。 If you wanted the below calls to behave differently, then explicitly implementing the interface would have made sense. 如果您希望以下调用具有不同的行为,那么显式实现该接口将是有意义的。

Customization oVar = new Customization();
oVar.GetColumnsDefinition(); // calls 1st method
ICustomization iVar = obj;
iVar.GetColumnsDefinition(); // calls 2nd method - explicit impl.

You should remove the explicit implementation. 您应该删除显式实现。 However if you remove the other implementation, you will constrain clients such that they can no longer call oVar.GetColumnsDefintion() - they would have to use an interface variable as shown above. 但是,如果删除其他实现,则会限制客户端,使其无法再调用oVar.GetColumnsDefintion() - 它们必须使用如上所示的接口变量。

For info, the main time you see that specific pattern is when (any one of): 有关信息,您看到特定模式的主要时间是(任何一个):

  • the non-explicit method is virtual or abstract , for subclasses to override 非显式方法是virtual方法或abstract方法,用于子类override
  • the signature of the public method is not quite the same, for example the public API has a more specific return type (common for things like IEnumerable[<T>] or ICloneable ). 所述的签名public方法是不太一样,例如公共API有更特定的返回类型(共同的东西等IEnumerable[<T>]ICloneable )。
  • we don't want it to be public , but we want it to be easily callable within the type (without needing a nop-cast) 我们不希望它是public ,但我们希望它在类型中可以轻松调用(不需要nop-cast)

In this case it does indeed look redundant. 在这种情况下,它确实看起来多余。

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

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