C#:代码契约与正常参数验证

C#:代码契约与正常参数验证,c#,.net,.net-4.0,code-contracts,microsoft-contracts,C#,.net,.net 4.0,Code Contracts,Microsoft Contracts,考虑以下两段代码: public static Time Parse(string value) { string regXExpres = "^([0-9]|[0-1][0-9]|2[0-3]):([0-9]|[0-5][0-9])$|^24:(0|00)$"; Contract.Requires(value != null); Contract.Requires(new Regex(regXExpres)

考虑以下两段代码:

    public static Time Parse(string value)
    {
        string regXExpres = 
           "^([0-9]|[0-1][0-9]|2[0-3]):([0-9]|[0-5][0-9])$|^24:(0|00)$";
        Contract.Requires(value != null);
        Contract.Requires(new Regex(regXExpres).IsMatch(value));
        string[] tokens = value.Split(':');
        int hour = Convert.ToInt32(tokens[0], CultureInfo.InvariantCulture);
        int minute = Convert.ToInt32(tokens[1], CultureInfo.InvariantCulture);
        return new Time(hour, minute);
    }

公共静态时间解析(字符串值)
{
如果(值==null)
{
抛出新的ArgumentNullException(“值”);
}
string[]tokens=value.Split(“:”);
if(tokens.Length!=2)
{
抛出新FormatException(“值必须为h:m”);
}
int hour=Convert.ToInt32(标记[0],CultureInfo.InvariantCulture);

如果(!(0为了消除警告,你可以使用这种方法来解决我的问题。如果我在return语句前面添加以下几行,所有错误的警告都消失了。我唯一不喜欢的是这些行以某种方式破坏了代码。但我想代码契约不可能理解regu的含义lar表达式。契约。假设(0@steveee,你应该总是在连词上拆分契约,这样
契约。假设(0@Porges)有文档解释原因吗?@ssg:我认为文档中没有,但是如果你搜索代码契约MSDN论坛,会有来自开发者的信息,例如:“将连词拆分为不同的契约可以使静态检查器更精确,并获得更好的错误消息。”您确实意识到可以重写第二个示例以使用相同的正则表达式,对吗?这将使两个示例更加相似。
    public static Time Parse(string value)
    {
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }
        string[] tokens = value.Split(':');
        if (tokens.Length != 2)
        {
            throw new FormatException("value must be h:m");
        }
        int hour = Convert.ToInt32(tokens[0], CultureInfo.InvariantCulture);
        if (!(0 <= hour && hour <= 24))
        {
            throw new FormatException("hour must be between 0 and 24");
        }
        int minute = Convert.ToInt32(tokens[1], CultureInfo.InvariantCulture);
        if (!(0 <= minute && minute <= 59))
        {
            throw new FormatException("minute must be between 0 and 59");
        }
        return new Time(hour, minute);
    }