什么是验证构造函数的参数的正确方法 [英] What is the correct way to validate the arguments of a constructor

查看:193
本文介绍了什么是验证构造函数的参数的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个类在其构造函数中有一个单一的字符串参数:

  public MyClass(s​​tring name)
{
this.Name = name;
}

但我从来不想担心一些初始化MyClass的实例即NULL或零长度字符串。最好的是验证参数?使用属性或方法,您可以始终只做无关,返回null,或者如果提供了无效的参数,则不设置任何内容。但是一旦构造函数被调用,对象的实例已经被创建,而不管它是否被传递了有效的参数。



抛出异常如下图所示的最好的方法?

  public MyClass(s​​tring name)
{
if (name == null | name ==)throw new ArgumentException(Name can not be null或blank,name);

this.Name = name;
}



当然,我可以将名称设置为一些默认值,如Unnamed MyClass如果参数无效,但在这种情况下,我宁愿只是阻止一个无效的名称,然后试图假设一些替代行为。

解决方案

ol>

  • 引发 ArgumentNullException

  • 记录ctor引发 ArgumentNullException 如果名称 null

  • 如果您使用代码合同,在参数验证后添加一个Contract.EndContractBlock()行。

  • 编辑:而不是这样:

      if (name == null || name ==)

    使用:

      if(string.IsNullOrEmpty(name))


    So I have a class with a single string parameter in its constructor:

    public MyClass(string name)
    {
        this.Name = name;
    }
    

    but I never want to worry about some one initializing an instance of MyClass with name that is NULL or a zero length string. What is the best was to validate the parameter? With a property or method you can always just do nothing, return null, or not set anything if an invalid argument is provided. But once a constructor is called the instance of the object is already created regardless of whether it was passed valid arguments.

    Is throwing an exception as shown below the best way? Or is there some other method that's more preferred?

    public MyClass(string name)
    {
        if (name == null | name == "") throw new ArgumentException("Name can not be null or blank", "name");
    
        this.Name = name;
    }
    

    Of course I could always set the name to some default like "Unnamed MyClass" if the argument is invalid, but in this case I'd rather just prevent an invalid name then trying to assume some alternate behavior.

    解决方案

    1. Throw an ArgumentNullException
    2. Document that the ctor throws ArgumentNullException if name is null
    3. If you are using Code Contracts, add a Contract.EndContractBlock() line after your parameter validation.

    Edit: Instead of this:

    if (name == null || name == "")
    

    Use this:

    if (string.IsNullOrEmpty(name))
    

    这篇关于什么是验证构造函数的参数的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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