How to hide an inherited property in a class without modifying the inherited class (base class)?

前端 未结 10 1144
无人共我
无人共我 2020-11-27 20:21

If i have the following code example:

public class ClassBase
{
    public int ID { get; set; }

    public string Name { get; set; }
}

public class ClassA :         


        
10条回答
  •  被撕碎了的回忆
    2020-11-27 20:28

    While technically the property won't be hidden, one way to strongly discourage its use is to put attributes on it like these:

    [Browsable(false)]
    [Bindable(false)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    [EditorBrowsable(EditorBrowsableState.Never)]
    

    This is what System.Windows.Forms does for controls that have properties that don't fit. The Text property, for instance, is on Control, but it doesn't make sense on every class that inherits from Control. So in MonthCalendar, for instance, the Text property appears like this (per the online reference source):

    [Browsable(false),
        EditorBrowsable(EditorBrowsableState.Never),
        Bindable(false), 
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public override string Text {
        get { return base.Text; }
        set { base.Text = value; }
    }
    
    • Browsable - whether the member shows up in the Properties window
    • EditorBrowsable - whether the member shows up in the Intellisense dropdown

    EditorBrowsable(false) won't prevent you from typing the property, and if you use the property, your project will still compile. But since the property doesn't appear in Intellisense, it won't be as obvious that you can use it.

提交回复
热议问题