无法在异常构造函数中写入字符串

时间:2009-02-16 15:54:01

标签: c# .net visual-studio-2008

当我将字符串传递给异常参数时,Visual Studio似乎会抱怨。

if (str1 == null || str2 == null)
{
    throw new ArgumentNullException("lmkl");
}

Visual Studio说它无法解析符号"lmkl"

如果我有一个字符串变量(例如,高于throw new... string s = "test";)并将其作为异常的参数包含在内,那么Visual Studio对此非常满意。

是什么给出了?

由于

3 个答案:

答案 0 :(得分:7)

ArgumentNullException的重载构造函数的文档,它带有一个字符串参数,表明该参数应为:

The name of the parameter that caused the exception.

目前,如果您的代码抛出异常,您将不知道哪个参数为null。

建议重写

if (str1 == null) throw new ArgumentNullException("str1");
if (str2 == null) throw new ArgumentNullException("str2"); 

答案 1 :(得分:7)

实际上,Visual Studio根本不关心 。我假设你安装了ReSharper?这样可以验证很多常见错误,包括错误使用ArgumentException等模式。它还有更好的null检查 - 不是“合同”,但仍然非常有帮助。

只有当它能够看到在已知模式中使用的字符串文字时才会尝试这种情况 - 分析如何分配变量对于实际分析来说太过分了。

答案 2 :(得分:0)

如果你正在使用ReSharper,这应该禁止警告(假设str1是你的param的名字):

throw new ArgumentNullException(nameof(str1));
相关问题