C# 使用参数';ArgumentException中的属性

C# 使用参数';ArgumentException中的属性,c#,sonarqube,C#,Sonarqube,我们的SonarQube经常在代码中提出以下问题(代码气味):“ArgumentException中使用的参数名称应该与现有名称匹配”。是触发此问题的规则 触发此问题的示例如下: private void Validate(SaveCommand command) { if(string.IsNullOrEmpty(command.UserCode)) throw new ArgumentNullException(nameof(command.UserCode));

我们的SonarQube经常在代码中提出以下问题(代码气味):“ArgumentException中使用的参数名称应该与现有名称匹配”。是触发此问题的规则

触发此问题的示例如下:

private void Validate(SaveCommand command)
{
    if(string.IsNullOrEmpty(command.UserCode))
        throw new ArgumentNullException(nameof(command.UserCode));
    ....
}
我的问题是:我如何正确地重构代码以遵守SonarQube(和)准则


或者我应该保持这样。如果是这样,原因是什么?

我认为SonarQube就在这里:没有名为
UserCode
的参数,因此不应该将其指定为
ArgumentNullException
构造函数的参数。在这里我将完全避免使用
ArgumentNullException
,因为参数不是null-否则它将在
命令处抛出
NullReferenceException

相反,只需使用带有描述性消息的
ArgumentException
,例如

throw new ArgumentException(
    $"{nameof(command.UserCode)} property cannot be null or empty",
    nameof(command));

现在我们可以知道哪个参数不正确(
command
),以及如何错误(它的
UserCode
proeprity为null或空)。SonarQube对此应该没问题,在我看来,它更准确地满足异常类型的含义。

太棒了!(Y) 谢谢!这很有道理:)