gpt4 book ai didi

c# - 契约(Contract) - 如何要求集合不包含空值

转载 作者:太空宇宙 更新时间:2023-11-03 15:43:57 27 4
gpt4 key购买 nike

我的类有一个内部属性返回 List<MyType> ,并且我想使用静态检查来帮助我不在我的程序集中做任何愚蠢的事情,并可能向该集合添加 null。

我在 foreach 的循环变量上收到这个静态警告在属性(property)上。

Warning 149 CodeContracts: Possibly calling a method on a null reference 'myLoopVariable'. Do you expect that System.Collections.Generic.List`1+Enumerator.get_Current returns non-null?

过去,我的集合中包含空值从未遇到过任何问题,但当编译器和我不同意时,这是对的,我是错的,因此我希望警告消失。这只是我以前想不到的,果然我可以做到MyClass.MyListProperty.Add(null) , 所以它确实有效。

我做不到Requires我在哪里使用循环变量,因为我得到了错误:

Contract section within a try block

它让我(没有任何错误)添加一个 Requires方法:

Contract.Requires<ArgumentException>(Contract.ForAll<MyClass>(MyClassInstance.MyListProperty, x => x != null))

但是,这并没有导致原来的警告消失,还产生了一个额外的警告:

Warning 149 CodeContracts: requires unproven: Contract.ForAll(MyClassInstance.MyListProperty, x => x != null)

我想知道是否有一种方法可以将该逻辑放在一个位置,靠近属性定义本身。

代码契约提供什么机制(如果有的话)来实现这一点?

编辑:

我开始认为我将不得不制作 MyListProperty再次私有(private),并限制对其的访问。否则,某人(我)可以添加 null给它! (但挑战是,如何允许“受信任”的访问者进行枚举?天哪!)

最佳答案

Assume 会收到消息,但我不确定这是否会导致性能问题,而且这似乎是多余的。不幸的是,我无法在不使用 Contract.Assume 的情况下摆脱静态检查器消息。

// at the beginning of your method
Contract.Requires(MyCollection != null && Contract.ForAll(MyCollection, x => x != null));
// other code
foreach(var item in MyCollection)
{
Contract.Assume(item != null);
// call method on item which can create a message from the static checker if the assume is not included
}

关于c# - 契约(Contract) - 如何要求集合不包含空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28996159/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com