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

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

最佳答案

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

关于c# - 构造函数和抛出异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8372545/

10-10 13:04