人生是一场不能存盘的RPG,我只能尽量多搞几个Screenshot

May 16, 2006

4种字符串判空的方法

Filed under: C#

1.  myStr.Length == 0

2.  myString == String.Empty

3.  myString==""

4.  String.IsNullOrEmpty (2.0)

在1.0时,FxCop推荐使用方法1,但为了防止null refrence,我们得先判一下null.

2.0有了新的静态方法IsNullOrEmpty(),那个最好呢?

使用Reflector打开.net 2,050727 下的mscorlib.dll

1 的代码为

[MethodImpl(MethodImplOptions.InternalCall)]
public extern int get_Length();

2和3  要使用了运算符==,而string的==的代码为

public static bool operator ==(string a, string b)
{
      return string.Equals(a, b);
}

string.Equals的代码为:

public static bool Equals(string a, string b)
{
      if (a == b)
      {
            return true;
      }
      if ((a != null) && (b != null))
      {
            return string.EqualsHelper(a, b);
      }
      return false;
}
看到这,你恐怕不会使用这种方法了吧.更有甚者myString==""还会先new一个空串出来.更浪费资源.

4 的代码为:

public static bool IsNullOrEmpty(string value)
{
      if (value != null)
      {
            return (value.Length == 0);
      }
      return true;
}

正是我们期待已久的答案.

Comments »

The URI to TrackBack this entry is: http://recordsome.blogsome.com/2006/05/16/p40/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.






















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham