📜  C#| IsNullOrEmpty()方法

📅  最后修改于: 2021-05-29 14:57:57             🧑  作者: Mango

在C#中, IsNullOrEmpty()是一个字符串方法。用于检查指定的字符串是否为null或Empty字符串。如果尚未为字符串分配值,则该字符串将为null 。如果为字符串分配了“”或String.Empty (空字符串的常量),则该字符串将为

句法:

public static bool IsNullOrEmpty(String str)  

说明:此方法将采用类型为System.String的参数,并且此方法将返回布尔值。如果str参数为null或空字符串(“”),则返回True,否则返回False。

例子:

Input : str  = null         // initialize by null value
        String.IsNullOrEmpty(str)
Output: True

Input : str  = String.Empty  // initialize by empty value
        String.IsNullOrEmpty(str)
Output: True

程序:演示IsNullOrEmpty()方法的工作原理:

// C# program to illustrate 
// IsNullOrEmpty() Method
using System;
class Geeks {
    
    // Main Method
    public static void Main(string[] args)
    {
        string s1 = "GeeksforGeeks";
      
        // or declare String s2.Empty;
        string s2 = ""; 
  
        string s3 = null;
  
        // for String value Geeks, return true
        bool b1 = string.IsNullOrEmpty(s1);
  
        // For String value Empty or "", return true
        bool b2 = string.IsNullOrEmpty(s2);
  
        // For String value null, return true
        bool b3 = string.IsNullOrEmpty(s3);
  
        Console.WriteLine(b1);
        Console.WriteLine(b2);
        Console.WriteLine(b3);
    }
}
输出:
False
True
True

注意: IsNullOrEmpty方法使您可以检查String是否为null或其值为Empty,并且其替代代码可以如下:

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

程序:演示IsNullOrEmpty()方法的替代方法

// C# program to illustrate the 
// similar method for IsNullOrEmpty()
using System;
class Geeks {
  
    // to make similar method as IsNullOrEmpty
    public static bool check(string s)
    {
        return (s == null || s == String.Empty) ? true : false;
    }
  
    // Main Method
    public static void Main(string[] args)
    {
        string s1 = "GeeksforGeeks";
  
        // or declare String s2.Empty;
        string s2 = ""; 
        string s3 = null;
  
        bool b1 = check(s1);
        bool b2 = check(s2);
        bool b3 = check(s3);
  
        // same output as above program
        Console.WriteLine(b1);
        Console.WriteLine(b2);
        Console.WriteLine(b3);
    }
}
输出:
False
True
True

参考: https : //msdn.microsoft.com/en-us/library/system。字符串.isnullorempty(v = vs.110).aspx