c# – 为什么基础Windows窗体的类与泛型类型停止设计器加载?

我试图拥有一个基本的 Windows Forms表单,它具有常用的功能和控件 – 而且还包含对需要类型为其方法的类的引用.每个表单都会代表不同的类型,所以我认为我可以按照这样做做一些事情:
public partial class Base<T> : Form where T : BaseClass
{
    private GenericHandler handler = new GenericHandler();
}

public class BaseClass { }

public class GenericHandler
{
    public void DoSomethingWithInstance<T>(T instance) where T : BaseClass
    {

    }
}

我的设计师类声明也反映了我的形式.现在当我做了代表Foo类型的第二个表单时,我无法访问设计器,因为我收到这个错误

The designer Could not be shown for this file because none of the
classes within it can be designed. The designer inspected the
following classes in the file: Foo — The base class
‘WindowsFormsApplication1.Base’ Could not be loaded. Ensure the
assembly has been referenced and that all projects have been built.

FooClass — The base class ‘WindowsFormsApplication1.BaseClass’
cannot be designed.

public partial class Foo : Base<FooClass>
{
    public Foo()
    {
        InitializeComponent();
    }
}

public class FooClass : BaseClass { }

为什么会发生这种情况/我做错了什么或有什么其他方法可以做到这一点?

解决方法

当Windows Form或用户UserControl加载到设计器中时,基本上设计者正在创建一个基类(您的自定义窗体或控件直接派生的类)的实例,然后手动/明确地执行InitializeComponents()方法反思,以建立您的控制的预期设计.

然而,在您的情况下,它不能创建基类的实例,因为它具有通用参数.如果您的表单或控件的基类是抽象的或没有认构造函数,则会发生同样的情况.在这种情况下,设计人员也将无法创建基类的实例.

a workaround这个使用TypeDescriptionProviderAttribute,你可以给设计师一个替代类,它应该实例化.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...