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

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

问题描述

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

 公共MyClass的(字符串名称)
{
this.Name =名称;
}



但我从来没有要担心某一个初始化MyClass的与名称实例这是空或零长度字符串。什么是最好的是验证参数?与属性或方法,你可以永远只是什么都不做,返回null,或者如果提供了无效的参数没有设置任何东西。但是,一旦一个构造函数被调用该对象的实例已经不管是否通过了有效的参数创建。



时抛出一个异常,如下图所示的最佳方式?或者是有没有更愿意在其他一些方法?



 公共MyClass的(字符串名称)
{
如果(名称== NULL |名称==)抛出新的ArgumentException(名称不能为空或空白,名);

this.Name =名称;
}



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


解决方案

  1. 抛出一个 ArgumentNullException

  2. 文件,该构造函数抛出 ArgumentNullException 如果的名称的是

  3. 如果您使用的代码契约的,你的参数验证后添加Contract.EndContractBlock()行



编辑:取而代之的是:

 如果(名== NULL ||名==)

使用这样的:

 如果(string.IsNullOrEmpty(名))


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天全站免登陆