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

后端 未结 7 2369
终归单人心
终归单人心 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:45

    1. When a new version of a Type implements a publicly-visible member whose name conflicts with a name you've used in a derived Type.

    2. To hide an inappropriate implementation in a base class from which you derive.

      For example KeyedCollection.Contains(TItem item) is inherited from Collection and is therefore an O(n) operation rather than the O(1) operation that KeyedCollection.Contains(TKey key) usually provides.

      This is arguably confusing as naive consumers may think the two are interchangeable.

      So it may be appropriate to implement a "better" version:

      public new bool Contains(TItem item)
      {
          if (item == null) throw new ArgumentNullException("item");
      
          return this.Contains(GetKeyForItem(item));
      }
      

提交回复
热议问题