C#中检查null的语法糖,非常实用

打印 上一主题 下一主题

主题 863|帖子 863|积分 2589

c#处理null的几个语法糖,非常实用。(尤其是文末Dictionary那个案例,记得收藏)
??
如果左边是的null,那么返回右边的操作数,否则就返回左边的操作数,这个在给变量赋予默认值非常好用。
  1. int? a = null;
  2. int b = a ?? -1;
  3. Console.WriteLine(b);  // output: -1
复制代码
 
??=
当左边是null,那么就对左边的变量赋值成右边的
  1. int? a = null;
  2. a ??= -1;
  3. Console.WriteLine(a);  // output: -1
复制代码
 
?.
当左边是null,那么不执行后面的操作,直接返回空,否则就返回实际操作的值。
  1. using System;
  2. public class C {
  3.     public static void Main() {
  4.         string i = null;
  5.         int? length = i?.Length;
  6.         Console.WriteLine(length ?? -1); //output: -1
  7.     }
  8. }
复制代码
 
?[]
索引器操作,和上面的操作类似
  1. using System;
  2. public class C {
  3.     public static void Main() {
  4.         string[] i = null;
  5.         string result = i?[1];
  6.         Console.WriteLine(result ?? "null"); // output:null
  7.     }
  8. }
复制代码
注意,如果链式使用的过程中,只要前面运算中有一个是null,那么将直接返回null结果,不会继续计算。下面两个操作会有不同的结果。
  1. using System;
  2. public class C {
  3.     public static void Main() {
  4.         string[] i = null;
  5.         Console.WriteLine(i?[1]?.Substring(0).Length); //不弹错误
  6.         Console.WriteLine((i?[1]?.Substring(0)).Length) // System.NullReferenceException: Object reference not set to an instance of an object.
  7.     }
  8. }
复制代码
 
一些操作
[code]//参数给予默认值if(x == null) x = "str";//替换x ??= "str";//条件判断string x;if(i
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

我爱普洱茶

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表