visual studio 设计器 不能实例化 抽象类的几种解决方案

来源:互联网 发布:金牛考勤网络连接 编辑:程序博客网 时间:2024/05/02 17:27

The designer must create an instance of type '<type name>', but it can't because the type is declared as abstract

问题产生的原因:

This error occurred because the base class of the object being passed to the designer is abstract, which is not allowed.


三种解决方案:

1. 使用 TypeDescriptionProvider  属性
[TypeDescriptionProvider(typeof(SubstituteBaseUserControlProvider))]
public abstract class BaseUserControl: UserControl

在抽象版本的类上加注特性
 [TypeDescriptionProvider(typeof(AbstractCommunicatorProvider))]
    public abstract  partial class Form1 : Form
这样基本可以解决vs设计器不能加载界面的毛病,注意我自己测试的结果比较有古怪,vs2010 net3.5 环境编译后并不能立刻就显示UI,我得把vs关闭后重新打开才能看到效果。
另外:我也测试了一下vs2012并不需要做上面的处理,他本身就支持抽象UI类的继承


2. 不实用 abstract 关键字
实现这些抽象方法 ( abstract method )并在方法中抛出异常

3. 使用一个中间类
假设有如下代码:
public class Form1 : BaseForm...public abstract class BaseForm : Form

将代码改成这样的形式:
public class Form1 : MiddleClass...public class MiddleClass : BaseForm... public abstract class BaseForm : Form... 
问题就会得到解决。

更进一步你可以在 Form1.cs用:

publicclass Form1
#if DEBUG  
 : MiddleClass
#else  
 : BaseForm
#endif

这样实际release的代码的行为与原代码并无区别

Tag:  在设计器中无法创建抽象的实例 2011-11-28 1:08 PM IS2120@CSDN
原创粉丝点击