C# 模数(%)运算符上的CodeContracts失败?
我正在编写一个专门的随机化器类,希望使用CodeContracts确保它的质量。典型的随机化器方法接收上限“max”,并返回低于该上限的正随机值C# 模数(%)运算符上的CodeContracts失败?,c#,.net,random,code-contracts,modulus,C#,.net,Random,Code Contracts,Modulus,我正在编写一个专门的随机化器类,希望使用CodeContracts确保它的质量。典型的随机化器方法接收上限“max”,并返回低于该上限的正随机值 public int Next(int max) { Contract.Requires<ArgumentOutOfRangeException>(0 <= max && max <= int.MaxValue); Contract.Ensures(0 <= Contract.Result&
public int Next(int max)
{
Contract.Requires<ArgumentOutOfRangeException>(0 <= max && max <= int.MaxValue);
Contract.Ensures(0 <= Contract.Result<int>());
Contract.Ensures(Contract.Result<int>() < maxValue);
return (int)(pick() % maxValue);
}
public int Next(int max)
{
合同。要求(0我无法重现您的问题。代码合同不会抱怨以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
namespace ContractModulo
{
class Program
{
UInt32 Pick()
{
return 0;
}
public int Next(int max)
{
Contract.Requires<ArgumentOutOfRangeException>(0 <= max && max <= int.MaxValue);
Contract.Ensures(0 <= Contract.Result<int>());
Contract.Ensures(Contract.Result<int>() < max);
return (int)(Pick() % max);
}
static void Main(string[] args)
{
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Diagnostics.Contracts;
名称空间收缩模
{
班级计划
{
UInt32 Pick()
{
返回0;
}
公共整数下一个(整数最大值)
{
合同。需要(0可能是因为maxValue!=max
。如果max==0
您的代码会引发异常。您的max
参数的名称也很糟糕,因为它不代表最大值,而是代表最大值加一。您的代码甚至无法编译。您的代码中有一个max
和一个maxValue
。maxValue是吗全局变量?@KevinCrowell即使是int
code合同类型的全局变量也不会抱怨。