C#:code合同与正常的参数验证 [英] C#: Code Contracts vs. normal parameter validation

查看:133
本文介绍了C#:code合同与正常的参数验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下两件code:

consider the following two pieces of code:

    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);
    }

    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);
    }

我个人preFER的第一个版本,因为code是更清晰和更小的,和合同可以很容易地关闭。但缺点是,Visual Studio的code分析责备,我应该检查空的参数值和构造的合同没有意识到,正则表达式确保分钟和小时是在给定boundarys之内。

I personally prefer the first version because the code is much clearer and smaller, and the Contracts can be easily turned off. But the disadvantage is that Visual Studio Code Analysis blames that I should check the parameter value for null and the Contracts of the constructor do not realize that the regex ensures that minute and hour are within the given boundarys.

所以我最终有很多错误的警告,我看不出有什么方法来验证字符串值与合同不结束了扔FormatExceptions以外的正则表达式验证。

So i end up having a lot of wrong warnings and I see no way to validate string values with contracts without ending up throwing FormatExceptions other than a RegEx validation.

任何建议使用code合同,你将如何解决这个和同等情形?

Any suggestions how you would solve this and equivalent situations using Code contracts?

推荐答案

为了摆脱的警告,你可以使用<一个href="http://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.contract.assume%28VS.100%29.aspx">Contract.Assume

In order to get rid of warnings you can use Contract.Assume

这篇关于C#:code合同与正常的参数验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆