构造函数和抛出异常

本文关键字:抛出异常 构造函数 | 更新日期: 2023-09-27 18:16:40

这是我中止对象实例化的最好方法,如果它的参数没有传入有效的数据?

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

构造函数和抛出异常

是。通常的做法是验证构造函数中的参数,如果它们无效则抛出异常。

很好。构造函数不返回任何东西,那么您如何知道是否出了问题呢?你可以有一个bool值将它设置为一些未初始化的状态,但我会使用异常。

:

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

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

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

如果您查看框架源代码,这正是微软所做的,所以我怀疑它是完全有效的。

在构造函数内部进行验证并在出现问题时抛出异常是完全可以的。