[英]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中隱藏。 但是這些方法仍然存在,並且仍然可以調用。 通常,無法禁止客戶端在類的實例上調用繼承的方法。
您有一些選擇:
EditorBrowsableAttribute
將隱藏智能感知的屬性 BrowsableAttribute
將隱藏屬性網格中的屬性 注意事項:
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.