Generic forms and VS designer

前端 未结 2 771
温柔的废话
温柔的废话 2021-01-14 08:02

I have a base class

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

and I want to derive a chil

2条回答
  •  隐瞒了意图╮
    2021-01-14 08:11

    Generics break the designer because it cannot instantiate the class without a type T. I explain a workaround in my blog post:

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

    In short, you need to "resolve" the type with an intermediary class:

    • BaseControl : UserControl
    • CustomerControl_Design : BaseControl
    • CustomerControl : CustomerControl_Design

    You can then conditionally switch this class out of the code based on the DEBUG or RELEASE compiler switches:

    #if DEBUG
    
    namespace MyNamespace
    {
        using System;
    
    
        public partial class CustomerEditorControl_Design : BaseEditorControl
        {
            public CustomerEditorControl_Design()
                : base()
            {
                InitializeComponent();
            }
        }
    }
    
    #endif
    
        public partial class CustomerEditorControl
    #if DEBUG
            : CustomerEditorControl_Design
    #else
            : BaseEditorControl
    #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 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.

提交回复
热议问题