多个参数和嵌套参数的 ArgumentException ParamName 约定

ArgumentException ParamName convention for multiple parameters and nested parameters

考虑到我有一个class如下:

class ProductPrice
{
   public string ProductName { get; set; }
   public decimal RegularPrice { get; set; }
   public decimal SalePrice { get; set; }
}

我有这样的功能:

public decimal CalculateDiscount(ProductPrice thePriceInfo)
{
   if (thePriceInfo.SalePrice > thePriceInfo.RegularPrice)
      throw new ArgumentException("Sale price cannot be greater than regular price.","?????");

   return (thePriceInfo.RegularPrice-thePriceInfo.SalePrice) / thePriceInfo.RegularPrice;
}

我想知道在调用 ArgumentException 的构造函数时应该为 ParamName 参数(上面的 ??????)输入什么。

我想知道在以下情况下 ParamName 的标准约定是什么:

1) 导致异常的参数嵌套在class中(即thePriceInfo.SalePrice)

2) 异常是由于两个不同参数之间的相互作用(在本例中 SalePrice 高于 RegularPrice)。你用逗号之类的分隔它们吗?

此外,ParamName 参数是否实际用于 .NET 本身或流行的第 3 方工具中的任何内容,或者它只是提供信息,供堆栈更上层的其他调用代码使用?

论证没有错,是论证的状态出了问题。我建议投NotSupportedException。来自 MSDN

For scenarios where it is sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed

我不能代表可能使用该数据的第三方工具,但我认为没有任何约定。 MSDN 建议它仅供参考:(对于最终用户,或者对于可能在更上游的另一个程序集中捕获它的开发人员,因此他们可以相应地处理它)

The content of paramName is intended to be understood by humans.

因此,设置您认为能够传达正确信息的任何值。 IMO,正常价格没有错,但促销价是错的,所以 "SalePrice" 或 "ProductPrice.SalePrice"。


如果我能观察一下...

这里实际上没有任何无效或超出范围的参数 - 只是指定一个金额不能小于另一个的业务规则。这不是例外,也不需要例外。

我会将您的逻辑分成两部分...一个验证价格,另一个计算折扣。

public bool IsDiscountValid(ProductPrice pp)
{
    return pp.SalePrice <= pp.RegularPrice;
}

public decimal CalculateDiscount(ProductPrice pp)
{
   return (pp.RegularPrice - pp.SalePrice) / pp.RegularPrice;
}

现在调用者可以以任何最适合您的程序的方式通知用户:

if (IsDiscountValid(thePriceInfo))
    return CalculateDiscount(thePriceInfo);

MessageBox.Show("Sale price cannot be greater than regular price.", "Invalid Price");

// or display text in a Label or whatever, depending on which platform you're using