簡體   English   中英

C#-從派生的方法中隱藏UserControl類的所有方法

[英]C# - Hiding all methods of the UserControl class from a derived one

我有一個自定義的用戶控件。 通常,它繼承UserControl類。 但是通過這種方式,它繼承了UserControl所有公共方法和屬性。 但是我想隱藏所有這些並實現我自己的一些方法和屬性。

假設我有一個名為CustomControl的自定義控件。

public class CustomControl : UserControl

當我創建CustomControl的實例時:

CustomControl cControl = new CustomControl();

當我鍵入cControl. intellisense為我提供了從UserControl派生的所有方法和屬性。 但是我只想列出在CustomControl類中實現的我的。

您可以創建一個接口,然后僅公開該接口的方法和屬性。

public interface ICustomControl {
     string MyProperty { get; set;}
}

public class CustomControl : UserControl, ICustomControl {
     public string MyProperty { get; set; }
}

...

ICustomControl cControl = new CustomControl();

然后,Intellisense僅顯示MyProperty和Object的成員(以及擴展方法,如果有的話)。

編輯:

protected ICustomControl CustomControl { get; set; }
    public Form1()
    {
        InitializeComponent();
        CustomControl = this.customControl1;
        CustomControl.MyProperty = "Hello World!"; // Access everything through here.
    }

然后,您可以根據需要將CustomControl的范圍設置為內部或受保護的內部。

繼承不是這樣工作的。 通過創建子類,您明確表示您希望訪問所有基類的方法和屬性。

為什么不使用組合並使UserControl成為自定義控件的成員,而不是從其繼承?

您可以通過在類中對其進行陰影處理(用關鍵字new聲明每個繼承的方法),然后將EditorBrowsableAttribute應用於它們,從而將它們從IntelliSense中隱藏。 但是這些方法仍然存在,並且仍然可以調用。 通常,無法禁止客戶端在類的實例上調用繼承的方法。

您有一些選擇:

  1. 使用EditorBrowsableAttribute將隱藏智能感知的屬性
  2. 使用BrowsableAttribute將隱藏屬性網格中的屬性
  3. 使用“ private new”隱藏屬性本身會將其隱藏

注意事項:

  1. 使用屬性將隱藏屬性,具體取決於“消費者”的實現,但是在語言級別,您沒有隱藏任何內容。 例如,您可以實現一個屬性網格,該網格在顯示屬性之前會檢查EditorBrowsableAttribute。 [我不確定Microsoft的Windows窗體實現]
  2. 使用“ private new”也將阻止您訪問屬性,盡管在控件內部您仍可以調用base.PropertyName來訪問原始屬性。

我明白你的意圖。 即使“繼承”繼承概念,通常也會限制繼承控件的行為。

不要繼承UserControl ,而是繼承Control

您可以通過聚合來做到這一點,例如

public CustomControl
{
    private Control control_;
    public property control {get{ return _control;}}
    .
    .
    .
    public void FunctionIWantExposed() {}
}

但這並不是特別有用。 您將無法將其添加到任何控件集合中。 您可以在自定義類控件中使用該屬性,並將其添加到ControlsCollection中,但是隨后您嘗試隱藏的所有這些方法將再次公開。

暫無
暫無

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

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