微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,你可以给设计师一个替代类,它应该实例化.

原文地址:https://www.jb51.cc/csharp/91535.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐