WinForm UserControl 的通用基类 [英] Generic base class for WinForm UserControl
问题描述
我为 WinForm UserControl 创建了一个通用基类:
I created a generic base class for a WinForm UserControl:
public partial class BaseUserControl<T> : UserControl
{
public virtual void MyMethod<T>()
{
// some base stuff here
}
}
以及基于此的 UserControl:
And a UserControl based on that:
public partial class MyControl : BaseUserControl<SomeClass>
{
public override void MyMethod<SomeClass>()
{
// some specific stuff here
base.MyMethod<SomeClass>();
}
}
它工作正常,但不能在 VisualStudio 设计器中编辑 MyControl,因为它说它不能加载基类.我试图定义另一个非通用类 BaseUserControl,希望它能加载它,但这个技巧似乎不起作用.
It works fine, but MyControl cannot be edited in the VisualStudio Designer, because it says it cannot load the base class. I tried to define another class BaseUserControl, non generic, hoping it would load it, but the trick doesn't seem to work.
我已经有了一个解决方法:定义一个接口,IMyInterface
I already have a workaround: define an interface, IMyInterface<T>, and then create my control as
public partial class MyControl : UserControl, IMyInterface<SomeClass>
但是我丢失了我的基本虚拟方法(没什么大不了的,但仍然......).
But I lose my base virtual methods (not a big deal, but still...).
有没有办法为 UserControl 创建一个通用基类,并且可以在 VisualStudio 设计器中对其进行编辑?
Is there a way to create a base generic class for a UserControl, with the possiblity to edit it in the VisualStudio Designer?
推荐答案
我们正在做同样的事情,我们通过首先专门化一个类并从专门化的类派生来解决这个问题.使用您示例中的代码,这意味着:
We're doing the same thing and we work around by specializing a class first and derive from the specialized class. Using the code from your example this means something like:
public partial class UserControl : UserControlDesignable
{
...
}
public class UserControlDesignable : BaseUserControl<Someclass> { }
设计师有时仍然表现得很古怪 - 但大多数时候它是有效的.
The designer is still acting flaky sometimes - but most of the time it works.
这篇关于WinForm UserControl 的通用基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!