c# - 是否有可能有一个抽象模板强制派生的专用构造函数?
问题描述
为了缩短问题,它有点简化。要点是强制从派生中独占调用所有基本构造函数,并禁止所有其他构造函数。
通过抽象模板强制使用一个独占构造函数:
public abstract class AbstractTemplatePattern
{
protected AbstractTemplatePattern(Foo foo)
{
// do the same work for every derived class
}
}
class DerivedTemplatePattern : AbstractTemplatePattern
{
// exclusive constructor forced by template (no others allowed)
public DerivedTemplatePattern(Foo foo) : base(foo) { }
// possible too, force calling the base contructor is the main thing here!
public DerivedTemplatePattern() : base(new Foo()) { }
public DerivedTemplatePattern(Bar bar) : base(new Foo()) { }
// not allowed constructor examples
public DerivedTemplatePattern() { }
public DerivedTemplatePattern(Bar bar) { }
}
对 n 个独占构造函数的明显扩展不会强制派生类中有 n 个独占构造函数,它只强制其中一个:
public abstract class AbstractTemplatePattern
{
protected AbstractTemplatePattern(Foo foo)
{
// do the same work for every derived class
}
protected AbstractTemplatePattern(Bar bar)
{
// do the same work for every derived class
}
}
class DerivedTemplatePattern : AbstractTemplatePattern
{
// no error, but this should not be allowed, as the template gives two constructors
public DerivedTemplatePattern(Foo foo) : base(foo) { }
}
是否可以使用抽象模板来实现这一点?
如果有帮助:实现工厂模式将是一种选择。
解决方案
推荐阅读
- swift - 如何确保在返回值之前获得 Firebase getDocument 结果?
- html - 我想在数据错误列旁边突出显示数据?我应该怎么办?
- javascript - 无法在构建期间使用 docker 在 next.js 中发送请求?
- r - 在ggplot2中使用组汇总值作为geom_ribbon?
- postgresql - 如何将表添加到 Debezium Postgres 连接器
- mysql - 如何更改 MySQL 根密码?
- fusioncharts - FusionCharts Column2D图表:如何设置y轴范围
- python - 如何使用 Python 和 Selenium 遍历网站正文
- python - 使用 for 循环时递归函数不起作用(Dijkstra 算法)
- r-markdown - 将列表转换为要点