Why to Use Explicit Interface Implementation To Invoke a Protected Method?

后端 未结 3 746
南笙
南笙 2021-01-02 05:29

When browsing ASP.NET MVC source code in codeplex, I found it is common to have a class explicitly implementing interface. The explicitly implemented method/property then in

3条回答
  •  無奈伤痛
    2021-01-02 06:04

    If a class implements IFoo.Bar explicitly, and a derived class needs IFoo.Bar to do something different, there will be no way for the derived class to call the base-class implementation of that method. A derived class which does not re-implement IFoo.Bar could call the base-class implementation via ((IFoo)this).Bar(), but if the derived class re-implements IFoo.Bar (as it would have to in order to change its behavior) the aforementioned call would go to the derived-class re-implementation, rather than the base-class implementation. Even ((IFoo)(BaseType)this).bar wouldn't help, since casting a reference to an interface type will discard any information about the type of the reference (as opposed to the type of the instance instance) that was cast.

    Having an explicit interface implementation do nothing but call a protected method avoids this problem, since a derived class can change the behavior of the interface method by overriding the virtual method, while retaining the ability to call the base implementation as it sees fit. IMHO, C# should have had an explicit interface implementation produce a virtual method with a CLS-compliant name, so someone writing in C# a derivative of a class that explicitly implemented IFoo.Bar could say override void IFoo.Bar, and someone writing in some other language could say, e.g. Overrides Sub Explicit_IFoo_Bar(); since any derived class can re-implement IFoo.Bar, and since any derived class which doesn't re-implement IFoo.Bar can call it on itself, I don't see that there's any useful purpose to having the explicit implementation be sealed.

    Incidentally, in vb.net, the normal pattern would simply be Protected Overridable Sub IFoo_Bar() Implements IFoo.Bar, without need for a separate virtual method.

提交回复
热议问题