Why can't I create an abstract constructor on an abstract C# class?

后端 未结 8 2135
无人及你
无人及你 2020-11-28 08:08

I am creating an abstract class. I want each of my derived classes to be forced to implement a specific signature of constructor. As such, I did what I would have done has I

8条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 08:52

    Although you can't override constructors, and therefore can't define an abstract constructor, you can place an abstract factory method in your abstract base class. All the derived classes would need to override that.

    public abstract class A 
    { 
        abstract A MakeAInstance(int a, int b); 
    } 
    
    public class B : A 
    { 
        // Must implement:
        override A MakeAInstance(int a, int b) {
            // Awesome way to create a B instance goes here
        }
    } 
    

提交回复
热议问题