ArgumentNullException、索引器和宪兵规则错误
我有索引器,想要检查它是否不为空,如果不为空,则抛出 ArgumentNullException,但 Gendarme 设置警告
InstantiateArgumentExceptionCorrectlyRule:此方法抛出 ArgumentException (或派生)异常而不指定现有的参数名称。这可以隐藏对开发人员有用的信息。修复异常参数以使用正确的参数名称(或确保参数的顺序正确)。
public override LocalizedString this[string key]
{
get
{
if (key == null)
{
throw new ArgumentNullException("key");
}
return base[key];
}
set
{
if (key == null || value == null)
{
throw new ArgumentNullException("key");
}
base[key] = value;
}
}
如何修复我的索引器?
I have the indexer and want to check if is it not null, and if it is then throw ArgumentNullException, but Gendarme sets the warning
InstantiateArgumentExceptionCorrectlyRule: This method throws ArgumentException (or derived) exceptions without specifying an existing parameter name. This can hide useful information to developers.Fix the exception parameters to use the correct parameter name (or make sure the parameters are in the right order).
public override LocalizedString this[string key]
{
get
{
if (key == null)
{
throw new ArgumentNullException("key");
}
return base[key];
}
set
{
if (key == null || value == null)
{
throw new ArgumentNullException("key");
}
base[key] = value;
}
}
How can I fix my indexer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,目前肯定是不对的。看看这个:
这意味着它会抛出一个异常,声称“key”为 null,而实际上它应该是“value”。
所以代码应该如下所示:
我不知道这是否会修复警告,但这将是正确的代码。
此错误报告表明这是一个错误宪兵尚未修复。如果您可以明确禁用该索引器的警告,这可能是最好的方法。 (我没有使用过宪兵,所以我不知道这是否可行,但值得研究一下。)
Well, it's definitely not right at the moment. Look at this:
That means it will throw an exception claiming "key" is null when it should actually be "value".
So the code should look like this:
I don't know whether that will fix the warning or not, but it would be the correct code.
This bug report suggests this is a bug in Gendarme which hasn't been fixed. If you can explicitly disable the warning just for that indexer, that's probably the best way to go. (I haven't used Gendarme so I don't know whether or not that's feasible, but it's worth looking into.)