簡體   English   中英

如何隱藏ASP.NET自定義控件的繼承屬性?

[英]How can I hide inherited properties of an ASP.NET custom control?

這是我第一次創建自定義控件的經驗。 我的實際示例更大,但為了清晰起見,將其簡化了下來。 最終,我需要隱藏盡可能多的自定義控件屬性,以便當我與團隊其他成員共享新控件時,他們只需要擔心所需的少數屬性。

我有一個名為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.
}

可行 ,但似乎很笨拙。 當我將控件放在網頁上時,我不再在智能感知中看到可用的文本,但是我確實收到一條警告,提示我的文本正在隱藏繼承的文本。 有沒有更好的方法來隱藏Text屬性?

該警告消息應該有更多內容,建議如果您確實打算隱藏繼承的成員,請使用new關鍵字,按照提示進行操作:

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

嘗試這個:

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

}

我認為如果您從行為類似於ITextControlLiteral派生ITextControl (文字已實現了此接口),然后嘗試刪除基本的Text屬性? 這就像衍生自貓,但又不想讓它們做“喵”聲並強迫它們像鴨子一樣飛翔。 我想,您正在搜索的是Animal類。

我對ASP.NET(台式機僅.NET)了解甚少。 也許可以使用合成代替繼承(如果您確實不需要Literal->“ Cat”),則可以從System.Web.UI.Control (->“ Animal”)繼承。

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進行了快速瀏覽,也許您正在尋找內容控件而不是文字控件 (對不起,如果寫錯了,請編寫桌面應用程序)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM