method hiding in c# with a valid example. why is it implemented in the framework? what is the Real world advantage?

前端 未结 6 1039
春和景丽
春和景丽 2020-12-05 19:53

Can anyone explain the actual use of method hiding in C# with a valid example ?

If the method is defined using the new keyword in the d

6条回答
  •  执笔经年
    2020-12-05 20:40

    One slightly obscure scenario where method hiding would be appropriate, but for a lack of any clean idiomatic way of expressing it, is in circumstances where a base class exposes a protected member to an inheritable descendant, but that descendant knows that there is no way any further derived classes could use that member without breaking things. A prime example of a method which many classes should hide (but very few do) is MemberwiseClone(). In many cases, if a class has a private member which expects to be the only extant reference to a mutable object, there is no possible means by which a derived class could ever use MemberwiseClone() correctly.

    Note that hiding of protected members does not constitute a violation of the LSP. Conformance with the LSP requires that in places where code might be expecting reference to a base-class object but receives a reference to a derived-class object, the latter object should work as would the base-class one. Protected members, however, are outside the scope of the LSP, since every type knows its base type absolutely. If Bar and Boz both derive from Foo, and Boz hides a protected member that Bar requires, the fact that Boz hides the member won't affect Bar, because Bar's base-type instance can't possibly be a Boz or anything other than Foo. No substitution is possible, and hence substitutability is irrelevant.

提交回复
热议问题