【问题标题】:String.IsNullOrBlank Extension MethodString.IsNullOrBlank 扩展方法
【发布时间】:2009-03-15 11:14:22
【问题描述】:

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

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.");
}

【问题讨论】:

    标签: c# extension-methods


    【解决方案1】:

    你可以这样做:

    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 实例上调用扩展方法。

    【讨论】:

    • 有趣的是,C# 不允许您调用具有空实例的方法,因为它会发出 callvirt IL 指令。但是,在 IL 中,如果您通过“调用”指令进行调用,则可以调用空实例。
    • @dan - 我不认为在其名称中暗示空检查的方法对扩展方法有不好的用途。
    • @Maslow - 同意。 C# 允许在 null 对象上使用扩展方法,因此请使用它。
    • 如果 this 参数为空,您可以从扩展方法中抛出 NullReferenceException 来模拟实例方法的行为,但提供比“对象引用未设置为对象。”
    【解决方案2】:

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

    【讨论】:

    【解决方案3】:

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

    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());
    

    虽然看起来有点奇怪,但我想弄清楚为什么你的字符串需要经常检查这种情况。如果你从源头上修复它们,你以后就不必对它们如此偏执了!

    【讨论】:

      【解决方案4】:

      你可以给现有的类添加静态方法吗?答案是否定的,而且值会很薄,因为您仍然需要知道首先输入哪个类名;使用扩展方法,优点是您从变量名开始,自动补全会显示适用于它的内容。

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

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

      【讨论】:

      • 不一样,IsNullOrEmpty 不检查只包含空白字符的字符串。
      • 另外,如果你调用 Trim() 并且字符串为空,你会得到一个 NullReferenceException。抱歉,答案没有多大价值,而且还具有误导性,所以 -1。
      • 问题是你不能修剪,直到你检查它是否为空,它又回到了第一方:(。我想我可以创建一个新的静态类并调用该方法而不是很高兴将它放在 String intellisense 上。
      • 我已经完全删除了第一部分,我同意它具有误导性。
      【解决方案5】:

      现有答案的过载可能是:

      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));
      

      【讨论】:

      • 任何样品使用您的方法?
      • @alhambraeidos - 完成,或者您正在寻找一个显示更具体/有用场景的示例?
      【解决方案6】:

      有点晚了。但是您也可以将代码放入扩展方法中以引发异常。我有两种方法(ArgumentNullException 和NullReferenceException)。

      // 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;
      }
      

      单元测试:

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

      然后将其用作:

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

      【讨论】:

        【解决方案7】:
        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;
        }
        

        【讨论】:

        • 如果被测试的字符串为 null 将不起作用,因为 Trim() 方法需要一个对象。
        • IsNullOrEmptyTrimmed(null);我认为会出错,因为 value.Length 为 null,抛出 NullReferenceException,不是吗?
        • 第一个例子不是返回 true 还是无限递归?
        • @pinkfloydx33:嗯.. 可能会。我忘记了。谢谢,已编辑。
        【解决方案8】:

        虽然这个问题是十多年前提出的,但我看到没有人提到有一个内置的字符串方法来处理这个问题。

        因此,请改用string.IsNullOrWhitespace()。没有破解任何东西,使用语言功能就可以了。

        【讨论】:

          【解决方案9】:

          通过一些技巧,您可以让它看起来像是添加到任何一个 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() 的“期望”语法。我并不一定建议您实际上以这种方式做事,只是指出您可以如何设置以使您的代码正常工作。

          【讨论】:

          • 这会引入大量的名称混淆。现在编码人员将不得不仔细检查该字符串是 JDanielSmith.String 还是 System.String...呃!
          • 上述的扩展方法显然更容易理解。 @code4life 是对的:呃!
          【解决方案10】:
          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 + "";
          }
          

          【讨论】:

          • 我觉得我不太喜欢这个。 IsNull 和 IsNotNull 的语义令人惊讶。为什么要在 ToStr 中将 string.Empty 添加到 o 中?
          • 它对对象更有用(例如当需要用 Eval("blalblabla") 做某事时),但也可以用于字符串。为什么你不喜欢这个?
          • 从概念上讲,(o == null) != (o.ToStr == string.empty)。如果我想测试 null 的引用,我最好只测试它的 null。 (我不是你的反对意见,只是说我想我理解它为什么会发生。)
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-09-15
          • 2010-09-09
          • 2020-02-29
          • 1970-01-01
          • 2010-10-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多