问题描述
我如何编写一个抽象类来告诉子类必须具有一个构造函数?
How can I write one abstract class that tells that is mandatory for the child class to have one constructor?
类似这样的东西:
public abstract class FatherClass
{
public **<ChildConstructor>**(string val1, string val2)
{
}
// Someother code....
}
public class ChildClass1: FatherClass
{
public ChildClass1(string val1, string val2)
{
// DO Something.....
}
}
更新1:
如果我不能继承构造函数.如何防止某人不会忘记实现特定的子类构造函数????
UPDATE 1:
If I can't inherit constructors. How can I prevent that someone will NOT FORGET to implement that specific child class constructor ????
推荐答案
您不能.
但是,您可以像这样在FatherClass上设置单个构造函数:
However, you could set a single constructor on the FatherClass like so:
protected FatherClass(string val1, string val2) {}
哪个会强制子类调用此构造函数-这会鼓励"它们提供 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);
}
}
无论何时需要创建FatherClass子类的实例,都可以使用IFooFactory而不是直接构造.这使您能够强制使用(字符串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.
这篇关于抽象类>子类的强制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!