我只是想了解一些关于Exceptions如何工作的更多细节。从MSDN ArgumentOutOfRangeException Constructor (String)页我找到字条:“这构造函数初始化使用PARAMNAME参数的新实例的PARAMNAME财产PARAMNAME的内容应为人理解。”ArgumentOutOfRangeException构造函数(字符串)定义
这究竟是什么意思呢? ArgumentException的字符串输入是否必须始终与方法定义输入名称匹配? (即双倍金额 - >“金额”)
如果是强制性的,如果方法输入参数更改了名称,字符串应该会自动更新,这样不便于维护。
从MSDN单元测试教程中,我们有以下代码:
public void Debit(double amount)
{
if (m_frozen)
{
throw new Exception("Account frozen");
}
if (amount > m_balance)
{
throw new ArgumentOutOfRangeException("amount");
//throw new ArgumentOutOfRangeException("whatever"); <-- this is my comment
//throw new ArgumentOutOfRangeException("what is the point?"); <-- this is my comment
}
if (amount < 0)
{
throw new ArgumentOutOfRangeException("amount");
}
m_balance -= amount;
}
因此,如果在某些时候方法的输入参数的名称发生更改,维护人员的最佳做法是更新Exception字符串呢?它不容易出错吗? – TasGeorg
更新字符串是有道理的,是的,这可能容易出错。为了这个目的,C#6添加了'nameof'运算符。你可以在'nameof(amount)'中使用它。 –