Is method hiding ever a good idea

前端 未结 8 1838
死守一世寂寞
死守一世寂寞 2020-12-01 09:29

In C# the new modifier can be used to hide a base class method without overriding the base class method.

I\'ve never encountered a situation where hidin

8条回答
  •  隐瞒了意图╮
    2020-12-01 09:42

    It's often a good choice when you're creating custom controls, and want to prevent certain properties from appearing in the designer. Sometimes the properties aren't overridable, but the designer doesn't care about that, it only cares whether or not the lowest-level public property has the [Browsable] attribute.

    For example, let's say that your control doesn't support padding. The Control.Padding property isn't overridable. But you also know that nothing bad is going to happen if somebody sets the padding, it's just that the property doesn't do anything, so you don't want your users to see it in the designer and think that it actually works. So, hide it:

    public class MyControl : Control
    {
        [Browsable(false)]
        public new Padding Padding
        {
            get { return base.Padding; }
            set { base.Padding = value; }
        }
    }
    

    In this case, we're literally using member hiding to hide the member - from the designer.

    As an aside, I'm aware that there are other means of achieving this goal - this is just one possible option.

提交回复
热议问题