码迷,mamicode.com
首页 > Windows程序 > 详细

C# 字符串判空(isNullOrEmpty)

时间:2015-08-18 12:29:05      阅读:822      评论:0      收藏:0      [点我收藏+]

标签:

string str 

  1:string.IsNullOrEmpty == str  这种方法是我最喜欢用的,它不但一次性能判断"空的字符串变量",还能判断“值为空字符串的变量”,并且还可以让代码简洁美观。判断的效率也不算低。

  2:str.Length == 0 这种方式,我不怎么喜欢用,不推荐使用。在网上看和自己的实际测试,确实能证明这种判断方式的执行效率最高,但要使用它你必须保证字符串不null,如果为null就会报出异常,

   3.str == string.Empty 或 str == "" 这两种方式,我也不推荐使用,他只能判断“值为空字符串”的字符串变量,而且效率比较低

  4.str == null 这种方式我也不怎么推荐,原因和3一样。

下面摘自微软官网:

String.IsNullOrEmpty 方法

指示指定的字符串是 null 还是 Empty 字符串。

public static bool IsNullOrEmpty(	string value
)

参数

返回值

类型:System.Boolean
如果 value 参数为 null 或空字符串 (""),则为 true;否则为 false

IsNullOrEmpty 是一种简便方法,它使您能够同时测试 String 是否为 null 或其值是否为 Empty 它与下列代码等效:

result = s == null || s == String.Empty;

可以使用 IsNullOrWhiteSpace 方法测试字符串是否 null,其值为 String.Empty,或仅包含空白字符。

using System;class Sample 
{    public static void Main() 
    {    string s1 = "abcd";    string s2 = "";    string s3 = null;

    Console.WriteLine("String s1 {0}.", Test(s1));
    Console.WriteLine("String s2 {0}.", Test(s2));
    Console.WriteLine("String s3 {0}.", Test(s3));
    }    public static String Test(string s)
    {    if (String.IsNullOrEmpty(s)) 
        return "is null or empty";    else
        return String.Format("(\"{0}\") is neither null nor empty", s);
    }
}



C# 字符串判空(isNullOrEmpty)

标签:

原文地址:http://my.oschina.net/isxiaoge/blog/493818

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!