在C# Winform窗體應用程序中,有時我們會繼承泛型Form/UserControl ,以達到部分控件或代碼可以重用的目的,但這往往會伴隨一個不太友好的問題:設計器無法可視化(出現一些異常,在此不一一列舉);這會給我們的界面布局帶來困擾。 目前,個人覺得最好的就絕辦法就是找一個“過渡的對象”,即在要繼承的Form/UserControl和被繼承的泛型Form/UserControl之間搭個橋,要繼承的Form/UserControl繼承“過渡的對象”,“過渡的對象”繼承泛型Form/UserControl,最終要繼承的Form/UserControl在設計器中就可以可視化了。關鍵代碼如下:
泛型Form/UserControl
/// <summary>
/// 承泛型Form/UserControl
/// </summary>
/// <typeparam name="TEntity">實體</typeparam>
/// <typeparam name="TInterface">實體對應接口</typeparam>
public partial class UCBaseGird<TEntity, TInterface> : UserControl
where TEntity : MongoDbEntity, new()
where TInterface : class
{
protected IBaseBll<TEntity> dataBll;
protected UCGridextend<TEntity> dataUC;
protected List<TEntity> dataList;
public UCBaseGird() { }
public UCBaseGird(IBaseBll<TEntity> dataBll, UCGridextend<TEntity> dataUC)
{
InitializeComponent();
//......
}
//......
}
“過渡的對象”
public class UCRoleMdiGird : UCBaseGird<RoleEntity, IRoleBll>
{
public UCRoleMdiGird() { }
public UCRoleMdiGird(IBaseBll<RoleEntity> dataBll, UCGridextend<RoleEntity> dataUC)
: base(dataBll, dataUC)
{ }
}
要繼承的Form/UserControl
public partial class UCRoleGird : UCRoleMdiGird {
public UCRoleGird(IBaseBll<RoleEntity> dataBll, UCGridextend<RoleEntity> dataUC) : base(dataBll, dataUC) { InitializeComponent(); //...... } //......
}