我有以下情况:
public interface ISomething
{
void DoStuff();
//...
}
public class Something : ISomething
{
private readonly ISomethingElse _somethingElse;
//...
public Something (ISomethingElse somethingElse)
{
Contract.Requires(somethingElse != null);
_somethingElse = somethingElse;
}
public void DoStuff()
{
// *1* Please look at explanation / question below
_somethingElse.DoThings();
}
}
在第1行并打开静态检查器,我会收到一条警告,说它_somethingElse
可能为空,如果我添加合同,它会给我错误
[Type] 实现接口方法 {Interface.Method} 因此不能添加要求
在这里做的最好的事情是什么?我看到的选项包括
- 一个保护条款,虽然它看起来有点极端
- 一种
Contract.Assume
- 我没有想到的隐藏的第三个选项
请注意,该字段readonly
在构造函数中设置值后无法更改。因此,来自代码合同的警告似乎有点无关紧要。