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

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

    Sometimes I make a class derived from something in the base class library, where the base class (for performance reasons) did not use a virtual function. In that case it makes sense to use 'new'. Here's one example (which matches what Marc Gravell was talking about), a strongly typed WeakReference:

    public class WeakReference : System.WeakReference
    {
        public WeakReference(T target) : base(target) { }
        public WeakReference(T target, bool trackResurrection) : base(target, trackResurrection) { }
        #if !WindowsCE
        protected WeakReference(SerializationInfo info, StreamingContext context) : base(info, context) {}
        #endif
        public new T Target
        {
            get { return (T)base.Target; }
            set { base.Target = value; }
        }
    }
    

    In cases where the base class method actually IS virtual, I think Microsoft was envisioning cases where the base class is implemented by one party and the derived class is implemented by a second party. The second party adds a function "Foo", then later the first party adds another function "Foo" that actually does something different (so overriding would not be appropriate). Then, in order to maintain compatibility with third party code, the second party keeps their function named "Foo" despite the fact that it is not directly related to the base class version. In that case, the second party adds "new" to their declaration.

提交回复
热议问题