相关疑难解决方法(0)

是否保证在调用链式构造函数之前评估代码合约?

在我开始使用代码约定之前,有时在使用构造函数链时会遇到与参数验证相关的繁琐.

这是一个(人为的)示例最简单的解释:

class Test
{
    public Test(int i)
    {
        if (i == 0)
            throw new ArgumentOutOfRangeException("i", i, "i can't be 0");
    }

    public Test(string s): this(int.Parse(s))
    {
        if (s == null)
            throw new ArgumentNullException("s");
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望Test(string)构造函数链接Test(int)构造函数,并使用int.Parse().

当然,int.Parse()不喜欢有一个null参数,所以如果s为null,它将在我到达验证行之前抛出:

if (s == null)
    throw new ArgumentNullException("s");
Run Code Online (Sandbox Code Playgroud)

这使得检查毫无用处.

如何解决?好吧,我有时习惯这样做:

class Test
{
    public Test(int i)
    {
        if (i == 0)
            throw new ArgumentOutOfRangeException("i", i, "i can't be 0");
    }

    public Test(string s): …
Run Code Online (Sandbox Code Playgroud)

c# code-contracts constructor-chaining

8
推荐指数
1
解决办法
327
查看次数

标签 统计

c# ×1

code-contracts ×1

constructor-chaining ×1