Abstract class > mandatory constructor for child classes [duplicate]

风格不统一 提交于 2021-02-07 12:28:43

问题


Possible Duplicate:
Why can’t I create an abstract constructor on an abstract C# class?

How can I write one abstract class that tells that is mandatory for the child class to have one constructor?

Something like this:

public abstract class FatherClass
{

    public **<ChildConstructor>**(string val1, string val2)
    {

    }

   // Someother code....
}

public class ChildClass1: FatherClass
{
    public ChildClass1(string val1, string val2)
    {
       // DO Something.....
    }
}

UPDATE 1:

If I can't inherit constructors. How can I prevent that someone will NOT FORGET to implement that specific child class constructor ????


回答1:


You cannot.

However, you could set a single constructor on the FatherClass like so:

protected FatherClass(string val1, string val2) {}

Which forces subclasses to call this constructor - this would 'encourage' them to provide a string val1, string val2 constructor, but does not mandate it.

I think you should consider looking at the abstract factory pattern instead. This would look like this:

interface IFooFactory {
    FatherClass Create(string val1, string val2);
}

class ChildClassFactory : IFooFactory
{
    public FatherClass Create(string val1, string val2) {
        return new ChildClass(val1, val2);
    }
}

Wherever you need to create an instance of a subclass of FatherClass, you use an IFooFactory rather than constructing directly. This enables you to mandate that (string val1, string val2) signature for creating them.




回答2:


The problem is that be default a non abstract / static class will always have a default empty public constructor unless you override it with private Constructor(){....}. I don't think you can force a constructor with 2 string params to be present in a child class.




回答3:


You do not inherit constructors. You would simply have to implement one yourself in every child class.




回答4:


You cant set a constructor as abstract, but you can do something like this:

 public abstract class Test
    {
        public Test(){}

        public Test(int id)
        {
            myFunc(id);
        }

        public abstract void myFunc(int id);
    }


来源:https://stackoverflow.com/questions/1393350/abstract-class-mandatory-constructor-for-child-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!