String.IsNullOrBlank扩展方法

时间:2009-03-15 11:14:22

标签: c# extension-methods

我不断检查字符串字段以检查它们是否为空或空白。

if(myString == null || myString.Trim().Length == 0)
{
    throw new ArgumentException("Blank strings cannot be handled.");
}

为了节省一些输入,可以为String类创建一个具有相同效果的扩展方法吗?我理解如何为类实例添加扩展方法,但是如何向类添加静态扩展方法呢?

if(String.IsNullOrBlank(myString))
{
    throw new ArgumentException("Blank strings cannot be handled.");
}

10 个答案:

答案 0 :(得分:36)

你可以这样做:

public static bool IsNullOrBlank(this String text)
{
  return text==null || text.Trim().Length==0;
}

然后像这样称呼它:

if(myString.IsNullOrBlank())
{
  throw new ArgumentException("Blank strings cannot be handled.");
}

这是有效的,因为C#允许您在null个实例上调用扩展方法。

答案 1 :(得分:16)

我知道这是一个古老的问题,但由于它已被提出并且尚未提及,因此从.NET 4.0开始,您只需使用String.IsNullOrWhiteSpace method即可获得相同的结果。

答案 2 :(得分:6)

您可以安全地在实例上使用扩展方法:

public static class StringExtensions
{
    public static bool IsNullOrBlank(this string s)
    {
        return s == null || s.Trim().Length == 0;
    }
}

测试用例:

string s = null;
Assert.IsTrue(s.IsNullOrBlank());
s = " ";
Assert.IsTrue(s.IsNullOrBlank());

虽然看起来有点奇怪,但我会想出为什么你的字符串需要经常检查这个案例。如果你在源头修复它们,你将不必在以后对它们如此偏执!

答案 3 :(得分:2)

您可以向现有类添加静态方法吗?答案是否定的,并且值很小,因为您仍然需要知道要先键入哪个类名;使用扩展方法,优点是您从变量名称开始,自动完成向您显示适用于它的内容。

经常提出的另一点是,如果第一个参数为null,扩展方法应该尽快抛出异常。但是,如果该方法在其名称中提到它旨在检查null,我认为该规则是过度的。

您遇到的真正问题是,在检查空引用后,您希望整齐且可读地运行一些代码。捕获该模式的一种方法是my answer to this question

答案 4 :(得分:2)

现有答案的重载可能是:

public static bool IsNullOrBlank(this String text, Action<String> doWhat)
{
  if (text!=null && text.Trim().Length>0)
    doWhat(text);
}

如果您只想运行给定有效值的代码,将会很有帮助。

不是一个非常有用的示例,只是显示用法:

Name.IsNullOrBlank(name=>Console.WriteLine(name));

答案 5 :(得分:1)

有点晚了。但是你也可以把代码放在扩展方法中抛出异常。我有两种方法(ArgumentNullExceptionNullReferenceException)。

// strings
public static bool NullBlankCheck(this string s, string message = "",
    bool throwEx = true)
{
    return Check<NullReferenceException>(s.IsNullOrBlank(), throwEx, message);
}
public static bool NullBlankCheckArgument(this string s, string message = "",
    bool throwEx = true)
{
    return Check<ArgumentException>(s.IsNullOrBlank(), throwEx, message);
}

private static bool Check<T>(bool isNull, bool throwEx, string exceptionMessage)
    where T : Exception
{
    if (throwEx && isNull)
        throw Activator.CreateInstance(typeof(T), exceptionMessage) as Exception;
    return isNull;
}

public static bool IsNullOrBlank(this string s)
{
    return string.IsNullOrEmpty(s) || s.Trim().Length == 0;
}

nunit测试:

Assert.Throws<NullReferenceException>(() =>
{
    "".NullEmptyCheck();
});
Assert.Throws<ArgumentException>(() =>
{
    "".NullEmptyCheckArgument();
});

然后将其用作:

public void Method(string someStr)
{
    someStr.NullBlankCheckArgument();
    // do something
    var str = someMethod();
    str.NullBlankCheck();
}

答案 6 :(得分:0)

public static bool IsNullOrEmptyTrimmed(string value)
{
    return (value == null || value.Length == 0) ?
        true :
        value.Trim().Length == 0;
}

public static bool IsNullOrEmpty(this String value, bool checkTrimmed)
{
    var b = String.IsNullOrEmpty(value);
    return checkTrimmed ? (b && value.Trim().Length > 0) : b;
}

答案 7 :(得分:0)

通过一些技巧,您可以在任何一个 cs 文件中将其添加到 String 类中:

namespace JDanielSmith
{
    public static class String
    {
        public static bool IsNullOrBlank(string text)
        {
            return text == null || text.Trim().Length == 0;
        }
    }
}

(注意,这是的扩展方法,请参阅我的评论)。

然后,在其他一些CS文件中:

using String = JDanielSmith.String;
namespace Foo.Bar.Baz
{
    class Program
    {
        static void test(string myString)
        {
            if (String.IsNullOrBlank(myString))
            {
                throw new ArgumentException("Blank strings cannot be handled.");
            }
        }
...

注意 String.IsNullOrBlank()的“所需”语法。我并不一定建议您实际上以这种方式做事,只是指出如何设置以使代码工作。

答案 8 :(得分:0)

尽管这个问题是在十多年前提出的,但我没有人提到有内置的字符串方法来处理此问题。

因此,请改用string.IsNullOrWhitespace()。无需进行任何入侵,使用语言功能就可以了。

答案 9 :(得分:-1)

public static bool IsNull(this object o)
{
    return string.IsNullOrEmpty(o.ToStr());
}

public static bool IsNotNull(this object o)
{
    return !string.IsNullOrEmpty(o.ToStr());
}

public static string ToStr(this object o)
{
    return o + "";
}
相关问题