EKsumic's Blog

let today = new Beginning();

Click the left button to use the catalog.

OR

C#Null

C#Null

普通的值类型不可为null。

比如int,默认会初始化为0。

C#有一种可空类型(nullable types)

来表示值类型的null。


比如

Nullable<int> a=null;

麻烦的写法不符合C#的风格,

于是有

int? a=null;

 

Nullable<T>的常用属性和方法
✦ .HasValue
✦ .Value
✦ .GetValueOrDefault()
✦ .GetValueOrDefault(默认值)

Nullable<T>类型转化为具体值类型需要显式转换。

 


Nullable<T>的具体应用场景

比如围棋的点,

有空、黑、白3种状态,

一般你会使用int值类型,

使用-1,0,1来代表空黑白3种状态。

但是有了Nullable<T>类型之后,

就可以使用Nullable<bool>来定义点的状态,

更加符合面向对象编程。

 

 

namespace Null
{
    class Program
    {
        static void TestNull(string str)
        {
            Console.WriteLine(string.IsNullOrEmpty(str));
            Console.WriteLine(string.IsNullOrWhiteSpace(str));
            Console.WriteLine();
        }
        static void Main(string[] args)
        {
            string str = "";
            string str2 = null;
            string str3 = "  "; //按了俩下Space
            string str4 = "   ";//按了俩下Space+Tab(tab到vs里面自动变空格)
            string str5 = "   /t";//按了俩下Space+Tab转义的tab
            TestNull(str);
            TestNull(str2);
            TestNull(str3);
            TestNull(str4);
            TestNull(str5);
            Console.Read();
            
        }
    }
}

输出:

True
True

 

True
True

 

False
True

 

False
True

 

False
False


经测试""和null相等,“”属于empty也属于null。

variable value IsNull IsEmpty IsWhiteSpace(Only) IsNullOrEmpty IsNullOrWhiteSpace
str "" Yes Yes No True True
str2 null Yes Yes No True True
str3 "  " No No Yes False True
str4 "   " No No Yes False True
str5 "   /t" No No No False False

 

IsNullOrEmpty和IsNullOrWhiteSpace的应用场景

一般先判断非空,再判断是否是单独的白空格。

 

 

NULL合并操作符

??操作符,

就是用来判定??左边是不是null,是的话就执行右边的逻辑,不是就短路。

 


NULL条件操作符

?操作符 

允许像写方法一样写在.前面,用来判断对象是否存在,不存在的话直接用个null代替,

存在的话,那就继续后面的方法。

一般用在不确定该值是否为null,怕因null调用方法出错。

 

区别

??操作符示例:

string s1="Something";
string s2=s1??"nothing";

最终表达式必须可以接受null。

 

?操作符示例:

StringBuilder sb=null;
string s=sb?.ToString();

?可以和??一起使用。

 

举例:

namespace Null关键字
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sb = null;
            string s = sb?.ToString() ?? "nothing";
            Console.WriteLine(s);
        }
    }
}

输出:

nothing

 

This article was last edited at 2020-03-19 04:06:35

* *