繁体   English   中英

构造函数和抛出异常

[英]Constructors and throwing exceptions

如果对象的参数未与有效数据一起传递,这是否是中止对象实例化的最佳方法?

protected Command(string commandKey)
{
    if(commandKey == null) throw new ArgumentNullException("commandKey", "Command Key cannot be null as it is required internally by Command");
    if(commandKey == "") throw new ArgumentException("Command Key cannot be an empty string");
    CommandKey = commandKey;
}

是。 通常的做法是在构造函数中验证参数,并在参数无效时引发异常。

很好 构造函数不返回任何内容,那么如果出现问题,您还怎么知道呢? 您可以将其设置为某些未初始化状态,但我会带有例外。

另外:

if(String.IsNullOrEmpty(commandKey)) //throw exectpion

在这种情况下,您可以使用静态方法string.IsNullOrEmpty(commandKey):

protected Command(string commandKey) 
{ 
    if(string.IsNullOrEmpty(commandKey))
        throw new ArgumentException("commandKey");
    //something
} 

如果您仔细阅读框架源代码,这正是Microsoft所做的事情,因此我怀疑它是完全有效的。

如果在构造函数中进行验证并在出现问题时引发异常,那将是非常好的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM