ArgumentException或ArgumentNullException为字符串参数? [英] ArgumentException or ArgumentNullException for string parameters?
问题描述
在最佳实践中,哪个更好:
Far as best practices are concerned, which is better:
public void SomeMethod(string str)
{
if(string.IsNullOrEmpty(str))
{
throw new ArgumentException("str cannot be null or empty.");
}
// do other stuff
}
或
public void SomeMethod(string str)
{
if(str == null)
{
throw new ArgumentNullException("str");
}
if(str == string.Empty)
{
throw new ArgumentException("str cannot be empty.");
}
// do other stuff
}
第二个版本似乎更精确,但也比第一个更麻烦。我通常去#1,但是我想检查是否有一个参数为#2。
The second version seems more precise, but also more cumbersome than the first. I usually go with #1, but figured I'd check if there's an argument to be made for #2.
推荐答案
我说第二种方式确实更精确 - 是的,这样比较麻烦,但是你可以随时把它包装起来,以避免一直都这样做。甚至可以是一个扩展方法:
I'd say the second way is indeed more precise - yes, it's more cumbersome but you can always wrap it in a method to avoid having to do it all the time. It could even be an extension method:
str.ThrowIfNullOrEmpty("str");
public static void ThrowIfNullOrEmpty(this string value, string name)
{
if (value == null)
{
throw new ArgumentNullException(name);
}
if (value == "")
{
throw new ArgumentException("Argument must not be the empty string.",
name);
}
}
另一种潜在有用的表单是返回原来的字符串,如果一切正常。你可以这样写:
Another form which is potentially useful is one which returns the original string if everything is okay. You could write something like this:
public Person(string name)
{
this.name = name.CheckNotEmpty();
}
另一个需要考虑的选项是使用代码合同作为替代您自己的例外。
Another option to consider is using Code Contracts as an alternative to throwing your own exceptions.
这篇关于ArgumentException或ArgumentNullException为字符串参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!