mentException或ArgumentNullExcept

mentException或ArgumentNullExcept

本文介绍了的ArgumentException或ArgumentNullException字符串参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅就最佳实践而言,这是更好的:

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字符串参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 02:32