代码合同1.4.40602.0 - Contract.ForAll似乎不起作用?

时间:2011-12-09 16:31:58

标签: c# collections code-contracts preconditions

Warning 1 CodeContracts: requires unproven: Contract.ForAll(coll, item => item != null) C:\MyApp\MyObj.cs

    public MyObj()
        : this(new Collection<Object>()) { }

    public MyObj(ICollection<Object> coll)
    {
        Contract.Requires<ArgumentNullException>(coll != null);
        Contract.Requires<ArgumentException>(Contract.ForAll(coll, item => item!= null));

        _coll = coll;
    }

我意识到在较旧版本的CodeContracts中,Contract.ForAll()方法不受支持,但我现在想(版本1.4.40602.0)会是吗?我在这里做错了还是仍然不支持?

2 个答案:

答案 0 :(得分:2)

我发现CodeContracts位缺乏语言和框架集成。

在这种情况下,您传入的集合明显地传递了条件,但是由于缺少C#语言集成(代码契约不理解您通过C#传入空集合),或者缺少.NET框架集成(Collection类未使用代码协定进行注释)。

答案 1 :(得分:2)

我没有在CC选项中将“警告级别”设置为“低”的警告。将值设置为“高”时,我收到了警告。

我已尝试System.Collections.ObjectModel.Collection<T>System.Collections.Generic.List<T>,并且都发出相同的警告。

我已经尝试了构造函数和常规方法调用 - 没有区别。

我试过

public MyObj() : this(new List<Object>()) { }

public MyObj() : this(new List<Object>{1}) { }

再次没有区别。

在进行常规方法调用时提取变量也无济于事。

即使Assume没有帮助:

public void M1()
{
  var list = new List<Object>
    {
      1
    };
  Contract.Assume(Contract.ForAll(list, t => t != null));
  this.X(list); // Still gives warning on the ForAll requirement
}

public void X(ICollection<object> c)
{
  Contract.Requires<ArgumentNullException>(c != null);
  Contract.Requires<ArgumentException>(Contract.ForAll(c, x => x != null));
}

(我在VS2010 SP1上使用相同的CC:1.4.40602.0)

<强>更新

使用数组。

也许,Judah Himango对于CollectionList上缺少合同是正确的。