如何隐藏ASP.NET自定义控件的继承属性?

时间:2015-08-31 17:06:53

标签: c# asp.net inheritance custom-controls

这是我创建自定义控件的第一次体验。我的真实例子要大得多,但为了清晰起见,这个问题已经过时了。最终,我需要尽可能多地隐藏自定义控件的属性,这样当我与团队的其他成员共享新控件时,他们只需要担心所需的几个属性。

我有一个名为TimeNow的控件,它继承System.Web.UI.WebControls.Literal,基本上只是打印网页上的当前时间:

public class TimeNow : Literal

// Set to private so Text is hidden from the editor.
private string Text
{
    get;
    set;
}

protected override void Render(HtmlTextWriter writer)
{
    // Get and write the time of now.
}

这个有效,但看起来很笨拙。当我将控件放在网页上时,我不再在intellisense中看到Text可用,但是我确实收到一条警告,说我的Text隐藏了继承的Text。有没有更好的方法来隐藏Text属性?

3 个答案:

答案 0 :(得分:1)

该警告消息应该有更多内容,建议您使用new关键字,如果确实打算隐藏继承的成员,请执行以下操作:

public class TimeNow : Literal
{
    new private string Text
    {
        get;
        set;
    }
}

答案 1 :(得分:0)

试试这个:

[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
private string Text
{

}

答案 2 :(得分:0)

如果您从Literal得到行为类似于ITextControl(Literal已实现此接口)然后您尝试删除基本Text属性,我认为您做错了什么?这就像是来自猫,但不想让他们这样做,喵喵叫#34;并强迫他们像鸭子一样飞翔。我想你正在寻找动物类。

我对ASP.NET(桌面只有.Net)了解不多。也许有可能使用合成而不是继承(如果你真的不需要Literal - >" Cat")并且你可以继承System.Web.UI.Control( - >" Animal&# 34;)而不是。

public class TimeNow : System.Web.UI.Control
{
   // no need to do something here with the Text property, is not defined
}

或与作文

public class TimeNow : System.Web.UI.Control
{
     private readonly Literal literal;

     public TimeNow()
     {
         this.literal = new Literal();
         // ... and set the Text etc., no one else can access
     }

     // or something like this

     public TimeNow(ILiteralFactory literalFactory)
     {
         // the factory is just an example... don't know your context but this way your newly created literal can't be accessed
         this.literal = literalFactory.CreateNewLiteral();
         // do what you want with the text control, e.g. store internally
         // Clone() the Literal etc.
         // the
     }
}

更新:快速查看MSDN,可能会找到Content Control,而不是文字。 (对不起,编写桌面应用程序)

相关问题