空体构造函数中的契约先决条件
早上好!我正在编写一个用于绘制直方图的类,为了方便用户,我决定添加一些方便的构造函数。
然而,当我最近从 DevLabs 切换到 .NET 代码合约时,我想充分利用先决条件来防止我自己(或某人)的愚蠢行为。
public HistoGrapher(IList<string> points, IList<T> values)
: this(points.Select((point, pointIndex) => new KeyValuePair<string, T>(point, values[pointIndex])))
{
Contract.Requires<ArgumentNullException>(points != null, "points");
Contract.Requires<ArgumentNullException>(values != null, "values");
Contract.Requires<ArgumentException>(points.Count == values.Count, "The lengths of the lists should be equal.");
}
public HistoGrapher(IEnumerable<KeyValuePair<string, T>> pointValuePairs)
{
// useful code goes here
}
有件事让我很困惑。如果合同被破坏,我不希望第一个构造函数调用第二个构造函数;但是,假设在执行第一个构造函数的主体之前将执行对 this(...)
的调用。
这段代码能按照我的要求工作吗?我还没试过。 如果没有,是否有能力解决这样的问题?
Good morning! I'm writing a class for drawing histograms and, for user's convenience, I've decided to add a few convenience constructors.
However, as soon as I recently switched to .NET code contracts from DevLabs, I want to make full use of preconditions for protection against my own (or someone's) stupidity.
public HistoGrapher(IList<string> points, IList<T> values)
: this(points.Select((point, pointIndex) => new KeyValuePair<string, T>(point, values[pointIndex])))
{
Contract.Requires<ArgumentNullException>(points != null, "points");
Contract.Requires<ArgumentNullException>(values != null, "values");
Contract.Requires<ArgumentException>(points.Count == values.Count, "The lengths of the lists should be equal.");
}
public HistoGrapher(IEnumerable<KeyValuePair<string, T>> pointValuePairs)
{
// useful code goes here
}
There is a thing that confuses me. I don't want the first constructor to ever call the second one if the contract is broken; however, it is supposed that a call to this(...)
will be performed before executing the body of the first constructor.
Will this code work as I want? I haven't tried yet.
And if not, is there a capability of solving such an issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于构造函数主体仅在调用其他构造函数之后执行,我认为您当前的方法不起作用。我建议将通用代码分解为一个单独的方法,即
Init()
,然后您可以从两个构造函数调用该方法,这将使您的代码保持干燥并解决您的问题:Since the constructor body is only executed after calling the other constructor I don't think your current approach can work. I would recommend factoring out the common code into a separate method i.e.
Init()
that you can then call from both constructors, that would keep your code DRY and solve your problem: