设计模式下的C#typed <T> usercontrol会出错

Mys*_*rth 7 c# generics user-controls types designmode

我有一个自定义类,源自UserControl.代码:

public partial class Gallery<T> : UserControl where T : class, IElement, new()
Run Code Online (Sandbox Code Playgroud)

这个类似于它应该工作的类.但是,当我尝试进入包含这些Gallery类的表单的设计模式时,它会给我错误:

  • 找不到类型'PresentrBuilder.Forms.Gallery'.请确保引用包含此类型的程序集.如果此类型是开发项目的一部分,请确保已成功构建项目.

  • 变量'pictureGallery'要么未声明,要么从未分配过.

注意:( pictureGallery实际上是Gallery<PictureElement>).

怎么解决这个?这样,我无法在设计模式下工作,这使得创建我的用户界面非常困难.

Mar*_*ell 12

设计师讨厌(即不支持)通用控件,并且不会很快改变,所以不要这样做.相反,考虑拥有一个接受a的属性(或类似)Type,并在运行时做一些工作(反射等) - 或者:不要使用设计器.

例如,如果您有:

public Type ControlType {get;set;} // comparable to T in the original
Run Code Online (Sandbox Code Playgroud)

您可以使用:

IElement el = (IElement) Activator.CreateInstance(ControlType);
Run Code Online (Sandbox Code Playgroud)

这将为您提供当前拥有的所有内容(new,IElement等) - 但它无法在编译时进行任何验证.


Ego*_*gor 11

在这种情况下,有时最简单的方法是创建一个限定泛型参数的空子类.

这通常使用ObservableCollection完成:

public class SomeItemCollection : ObservableCollection<SomeItem>{

}
Run Code Online (Sandbox Code Playgroud)

这有点刺激,但它可以解决你的问题.