Abstract generic UserControl inheritance in Visual Studio designer

后端 未结 1 946
太阳男子
太阳男子 2020-12-21 02:26

In one of my projects I\'m using an abstract UserControl. To be able to design this control in Visual Studio I\'m using the code proposed in this answer. Now I want to use t

相关标签:
1条回答
  • 2020-12-21 02:41

    I suppose you have a control AbstractGenericBase<T> : GenericBase<T> which GenericBase<T> is a control having such definition: GenericBase<T>: UserControl.

    So if you want to show AbstractGenericBase<T> in designer, you can use this code:

    using System.ComponentModel;
    using System.Windows.Forms;
    
    #if DEBUG
    public abstract partial class AbstractGenericBase<T> : NonGenericBase
    #else
    public partial class AbstractGenericBase<T> : GenericBase<T>
    #endif
    {
        public AbstractGenericBase()
        {
            InitializeComponent();
        }
    }
    #if DEBUG
    public class NonGenericBase : GenericBase<object> { }
    #endif
    

    Note

    • The goal is showing this class in designer:
      public abstract partial class AbstractGenericBase<T> : GenericBase<T>
    • If T has some type constraints, instead of object in GenericBase<object> use a Dummy which satisfies the generic constraints.
    • The solution is based on this fact: When the designer wants to show your control in design surface, it tries to create an instance of base class of your control. When the base class of your control is a generic class the designer doesn't know how to create an instance of base class.
      In above solution, for design-time support, we said to designer the base for our control is NonGenericBase, but for run-time, we keep GenericBase<T> as base class of our control.
    0 讨论(0)
提交回复
热议问题