简体   繁体   English

构造函数和抛出异常

[英]Constructors and throwing exceptions

Is this the best way for me to abort instantiation of an object if it's parameters are not passed in with valid data? 如果对象的参数未与有效数据一起传递,这是否是中止对象实例化的最佳方法?

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;
}

Yes. 是。 It is common practice to validate the arguments in constructors and throw an exception if they are invalid. 通常的做法是在构造函数中验证参数,并在参数无效时引发异常。

It's perfectly fine. 很好 Constructors do not return anything so how else would you know if something went wrong? 构造函数不返回任何内容,那么如果出现问题,您还怎么知道呢? You could have a bool to set it to some uninitialized state but I would go with exceptions. 您可以将其设置为某些未初始化状态,但我会带有例外。

Also : 另外:

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

In this case you could use the static method string.IsNullOrEmpty(commandKey): 在这种情况下,您可以使用静态方法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