我只是想了解有关异常如何工作的更多详细信息。来自 MSDN 页面 ArgumentOutOfRangeException Constructor (String)我发现注释:“此构造函数使用 paramName 参数初始化新实例的 ParamName 属性。paramName 的内容旨在被人类理解。”
这到底是什么意思? ArgumentException 的字符串输入是否必须始终与方法定义输入名称匹配? (即双倍金额 --> “金额”)
如果这是强制性的,如果方法输入参数更改了名称,字符串应该以某种方式自动更新以维护目的不是更容易吗?
从 MSDN unitTesting 教程我们有以下代码:
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;
}
请您参考如下方法:
What does this really mean?
这意味着作为 paramName 传递的参数 应该是 导致异常的实际参数。为什么?因为如果抛出异常,则意味着您的程序遇到了错误行为,这有助于了解哪个参数超出了其范围。
If it is obligatory, wouldn't be easier for maintenance purposes that the string should be automatically updated somehow if the method definition changed?
是的,肯定会。这正是 C# 6 引入 nameof operator 的原因。 :
public void Foo(int amount)
{
if (amount < balance)
throw new ArgumentOutOfRangeException(nameof(amount));
}
