什么是验证构造函数的参数的正确方法 [英] What is the correct way to validate the arguments of a constructor
问题描述
所以我有一个类在其构造函数中有一个单一的字符串参数:
public MyClass(string name)
{
this.Name = name;
}
但我从来不想担心一些初始化MyClass的实例即NULL或零长度字符串。最好的是验证参数?使用属性或方法,您可以始终只做无关,返回null,或者如果提供了无效的参数,则不设置任何内容。但是一旦构造函数被调用,对象的实例已经被创建,而不管它是否被传递了有效的参数。
抛出异常如下图所示的最好的方法?
public MyClass(string name)
{
if (name == null | name ==)throw new ArgumentException(Name can not be null或blank,name);
this.Name = name;
}
当然,我可以将名称设置为一些默认值,如Unnamed MyClass如果参数无效,但在这种情况下,我宁愿只是阻止一个无效的名称,然后试图假设一些替代行为。
ol>
ArgumentNullException
ArgumentNullException 如果名称是 null
编辑:而不是这样:
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.
- Throw an
ArgumentNullException
- Document that the ctor throws
ArgumentNullException
if name isnull
- 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屋!