C#中的条件判断(?,??等等)

来源:互联网 发布:海量数据存储 编辑:程序博客网 时间:2024/05/16 14:42

null值判断

 static void Main(string[] args)        {            string source = null;            string test = source ?? "null";            Console.WriteLine(test);            Console.ReadKey();        }

“??”两个问号表示null值得判断,在本例中,对test字符串进行判断,如果source为null,则test为“null”;如果source不为null,则取source的值。

真值判断

 static void Main(string[] args)        {            int x = 1;            int y = 2;            string result = x < y ? "true" : "false";            Console.WriteLine(result);            Console.ReadKey();        }

如果x

C#6.0的Null-Conditional Operator

 static void Main(string[] args)        {            string test = null;            string temptest = test?.ToUpper()??"shit";            Console.WriteLine(temptest);            Console.ReadKey();        }

在我们使用一个对象的属性的时候,有时候第一步需要做的事情是先判断这个对象本身是不是null,不然的话你可能会得到一个System.NullReferenceException 的异常。虽然有时候我们可以使用三元运算符string name = person != null ? person.Name : null;来简化代码,但是这种书写方式还是不够简单……由于null值检测时编程中非常常用的一种编码行为,so,C#6为我们带来了一种更为简化的方式。

原创粉丝点击