4

我有一个基类

internal partial class View<T> : UserControl
  where T : class
{
    protected T t;
}

我想从 View 派生一个孩子

internal partial class ViewChild<T> : View<T>
  where T : class
{
}

它工作正常,但我无法在 VS 设计器中编辑 ViewChild。我知道问题是通用基类。但是,我不明白在这种情况下如何避免这种情况。有没有办法解决这个问题?

4

2 回答 2

3

还有另一种方法,它不依赖于编译器标志:

http://wonkitect.wordpress.com/2008/06/20/using-visual-studio-whidbey-to-design-abstract-forms/

我真的不建议使用条件编译。使用框架要好得多,而不是反对它。

基本上,你可以通过现有的框架给VS一个不同的类。你用 TypeDescriptionProvider 属性装饰你的基类,它告诉 VS 使用不同的类作为设计器。

正如在原始博客文章中提到的,可能存在与此解决方法相关的警告,但我在一个具有 > 25 个从公共基类继承的 UserControls 的项目中巧妙地工作。

于 2012-04-18T08:16:05.433 回答
2

泛型破坏了设计器,因为它无法实例化没有类型的类T。我在我的博客文章中解释了一种解决方法:

http://adamhouldsworth.blogspot.co.uk/2010/02/winforms-visual-inheritance-limitations.html

简而言之,您需要使用中间类“解析”类型:

  • BaseControl<T> : UserControl
  • CustomerControl_Design : BaseControl<Customer>
  • CustomerControl : CustomerControl_Design

DEBUG然后,您可以根据或RELEASE编译器开关有条件地将此类从代码中切换出来:

#if DEBUG

namespace MyNamespace
{
    using System;


    public partial class CustomerEditorControl_Design : BaseEditorControl<Customer>
    {
        public CustomerEditorControl_Design()
            : base()
        {
            InitializeComponent();
        }
    }
}

#endif

    public partial class CustomerEditorControl
#if DEBUG
        : CustomerEditorControl_Design
#else
        : BaseEditorControl<Customer>
#endif
    {
    }

This will let you open the derived class of CustomerControl, unfortunately you will never be able to design a UI control with generics in the signature. My solution is only enabling the design of derived items.

I have no idea why CustomerControl : BaseControl<Customer> won't work as in this case the type T is defined, but it simply doesn't - I'm guessing because of the rules of generic usage.

To their defense, Microsoft do say that this isn't supported.

于 2012-04-18T08:08:43.830 回答