判断string是否为空

1. string str=null

初始化但不分配地址。

2. string str=""

初始化并分配地址,内部储存空字符串。

3. string str=string.Empty

string.Emptyprivacy static readonly类型的数据,内部值同样为""
但是和""又有些不同:

void SomeMethod(int ID, string value = string.Empty)
// Error: Default parameter value for 'value' must be a compile-time constant
{
    //... implementation
}
string str = "";

静态成员无法作为函数参数

switch(str)
{
    case string.Empty: // Error: A constant value is expected. 
        break;

    case "":
        break;

}

switch的参数只能为常量

[Example(String.Empty)]
// Error: An attribute argument must be a constant expression, typeof expression 
//        or array creation expression of an attribute parameter type

道理同上

4. 判断是否为空的最好办法其实还是string.Length==0

posted @ 2021-08-03 15:38  none323  阅读(515)  评论(0)    收藏  举报