代码合约警告“假设”可能失败称呼
在我的一个类中,我有一个 ExpandoObject
类型的私有字段。该字段在构造函数 (this.expected = new ExpandoObject()
) 中初始化,因此我确信它永远不会为 null
。
因此,在此类的其中一个方法中,我可以
Contract.Assumes(this.expected != null)
在使用 this.expected
执行任何操作之前安全地进行添加,因此代码契约不必担心可能对 null 对象的调用。但是,我收到一条警告,而不是对空引用可能进行方法调用的警告
对方法“Assume”的动态分派调用可能在运行时失败,因为一个或多个适用的重载是条件方法
方法签名和前几行代码如下所示:
protected void Expect(object values)
{
Contract.Requires<ArgumentNullException>(values != null);
Contract.Assume(this.expected != null);
var exp = (ICollection<KeyValuePair<string, object>>)this.expected;
在第三行,我收到警告
CodeContracts:可能在空引用“OddEnds.Testing.TestBase.o_SiteContainer0.<>p_Site3.Target”上调用方法
,其中我假设空引用的奇数签名是因为 exp
是一个动态对象。
我该如何解决这些问题?
In a class of mine, I have a private field of type ExpandoObject
. The field is initialized in the constructior (this.expected = new ExpandoObject()
), so I'm confident that it will never be null
.
Thus, in one of the methods on this class, I fell safe to add
Contract.Assumes(this.expected != null)
before using this.expected
for anything, so Code Contracts won't have to worry about possible calls on null objects. However, instead of a warning for possible method call on a null reference, I get a warning saying
The dynamically dispatched call to method 'Assume' may fail at runtime because one or more applicable overloads are conditional method
The method signature and the first few lines of code looks like this:
protected void Expect(object values)
{
Contract.Requires<ArgumentNullException>(values != null);
Contract.Assume(this.expected != null);
var exp = (ICollection<KeyValuePair<string, object>>)this.expected;
On the third line, I get a warning for
CodeContracts: Possibly calling a method on a null reference 'OddEnds.Testing.TestBase.o_SiteContainer0.<>p_Site3.Target'
where I assume the odd signature of the null reference is because exp
is a dynamic object.
How do I solve these?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为解决您的问题的最佳方法是声明
expected
永远不会为 null 作为类的不变量:当您执行此操作时,静态检查器将检查
expected
在构造函数末尾不为 null,然后它就会知道在任何其他方法开始时expected
永远不会为 null。I think the best way to solve your problem is to declare that
expected
is never null as an invariant on the class:When you do this, the static checker will check that
expected
is not null at the end of your constructor, and then it will know thatexpected
is never null at the start of any other method.我认为以下代码更改将使编译器满意(如果您确定要进行此转换,但为什么要使用 Expandoobject 那么..无论如何)
Im thinking following code change will keep compiler happy (if your sure in this cast anyway, but why use expandoobject then.. anyway)