C# Winform窗体应用程序中 继承泛型Form/UserControl 后,设计器无法可视化。

在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&lt;RoleEntity&gt; dataBll, UCGridextend&lt;RoleEntity&gt; dataUC)
    : base(dataBll, dataUC)
{
    InitializeComponent();
    //......
}
//......

}


注意:以上各类中(要继承的Form/UserControl除外),无参构造是必须的;有参构造分情况而定,目前知道的有两种情况:

1.泛型Form/UserControl有有参构造的,相应的另外两个也必须有,且要继承父类的有参构造。
2.泛型Form/UserControl有protected 全局变量(变量在使用),应在泛型Form/UserControl中添加有参构,造相应的另外两个也必须有,且要继承父类的有参构造,否则可能会报空指针异常。
posted @ 2015-11-23 17:09  元小宇  阅读(2860)  评论(0编辑  收藏  举报