Valid applications of member hiding with the new keyword in c#

后端 未结 7 2342
终归单人心
终归单人心 2021-02-18 16:22

I\'ve been using c# since version 1, and have never seen a worthwhile use of member hiding. Do you know of any?

7条回答
  •  不知归路
    2021-02-18 16:57

    Scenario #1:

    Imagine you are designing the runtime library for .NET 2.0. You now have generics at your disposal. You have an interface:

    interface IEnumerable 
    {
        IEnumerator GetEnumerator();
    }
    

    You wish to make a new interface

    interface IEnumerable 
    {
        IEnumerator GetEnumerator();
    }
    

    You now have three choices.

    1) Make the generic version unrelated to the non-generic version.

    2) Make the generic version extend the non-generic version. You now have two methods that differ only in return type. Change the name of GetEnumerator in the new type to GetEnumerator2(). Because that's hot. Everyone loves a good "2" method.

    3) Make the generic version extend the non-generic version. Make the new and improved method hide the existing method so that its there if you need it, but hidden by default.

    These are all bad choices. Which would you choose? We chose (3). Good thing that it was an option; without hiding, that option would not have been available.

    Now, you might argue that this particular example of hiding was not 'worthwhile'; if that's so, what would you have done instead?

    Method hiding makes it possible to expose improved interfaces without causing breakages when there are improvements to the type system.

    Scenario #2:

    You work at FrobCo. You produce a class Frobber that extends Blobber, which is supplied to you by the good people at BlobCo.

    BlobCo has neglected to put a Frobozzle() method on Blobber, but your customers love to frobozzle frobbers, so you add a method Frobozzle() to derived class Frobber.

    BlobCo realizes that their customers want to Frobozzle blobbers, so they add a non-virtual method Frobozzle() to Blobber, the base class.

    Now what do you do, FrobCo employee?

    1) Remove the Frobozzle method on Frobber, thereby breaking your customers who relied on your implementation. Remember, BlobCo doesn't know how to Frobozzle a Frobber; they only wrote code that knows how to Frobozzle a Blobber.

    2) Whine to BlobCo that they should have made their method virtual. Hope they do something about it someday.

    3) Hide their method in your derived class.

    Method hiding helps mitigate the brittle base class problem.

    Further Reading:

    http://blogs.msdn.com/ericlippert/archive/2008/05/21/method-hiding-apologia.aspx

提交回复
热议问题