Abstract UserControl inheritance in Visual Studio designer

前端 未结 9 1381
广开言路
广开言路 2020-12-01 12:13
abstract class CustomControl : UserControl 
{
    protected abstract int DoStuff();
}

class DetailControl : CustomControl
{
    protected override int DoStuff()
            


        
9条回答
  •  爱一瞬间的悲伤
    2020-12-01 12:29

    I just make the abstract base class into a concrete one by defining the "abstract" methods as virtual, and throwing an exception in them, just in case any naughty derived classes try to call Base implementation.

    e.g.

        class Base : UserControl
        {
            protected virtual void BlowUp()
            {
                throw new NotSupportedException("This method MUST be overriden by ALL derived classes.");
            }
    
        class Derived : Base
        {
            protected override void BlowUp()
            {
                // Do stuff, but don't call base implementation,
                // just like you wouldn't (can't actually) if the Base was really abstract. 
                // BTW - doesn't blow up any more  ;)
            }
    

    The main practical difference between this and a real abstract base class is you get run time errors when calling the base implementation - whereas if the Base was actually abstract, the compiler would disallow an accidental calls to the Base class implementation. Which isn't a big deal for me and allows me to use the designer without worrying about more complex and time consuming work arounds suggested by others...

    PS - Akuma - you should be able to edit your abstract UI class in the designer. I don't have time to check this right now, but it is my understanding that the designer only needs to instantiate the BASE class. As long as the base of the class you are designing is concrete, it doesn't matter what the designed class is.

提交回复
热议问题