C#6 新增特性目录

1. 老版本的代码

 1 namespace csharp6
 2 {
 3     internal class Person
 4     {
 5         public string Name { get; set; }
 6     }
 7 
 8     internal class Program
 9     {
10         private static void Main()
11         {
12             Person person = null;
13             //if判断
14             string name = null;
15             if (person != null)
16             {
17                 name = person.Name;
18             }
19         }
20     }
21 }

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

2. null条件运算符

 1 namespace csharp6
 2 {
 3     internal class Person
 4     {
 5         public string Name { get; set; }
 6     }
 7 
 8     internal class Program
 9     {
10         private static void Main()
11         {
12             Person person = null;
13             string name = person?.Name;
14         }
15     }
16 }

从上面我们可以看出,使用 ?. 这种方式可以代替if判断和简化三元运算符的使用,简洁到不能再简洁了吧。按照惯例,上两份IL代码对比对比。

老版本的IL代码:

 1 .method private hidebysig static void  Main() cil managed
 2 {
 3   .entrypoint
 4   // Code size       23 (0x17)
 5   .maxstack  2
 6   .locals init ([0] class csharp6.Person person,
 7            [1] string name,
 8            [2] bool V_2)
 9   IL_0000:  nop
10   IL_0001:  ldnull
11   IL_0002:  stloc.0
12   IL_0003:  ldnull
13   IL_0004:  stloc.1
14   IL_0005:  ldloc.0
15   IL_0006:  ldnull
16   IL_0007:  cgt.un
17   IL_0009:  stloc.2
18   IL_000a:  ldloc.2
19   IL_000b:  brfalse.s  IL_0016
20   IL_000d:  nop
21   IL_000e:  ldloc.0
22   IL_000f:  callvirt   instance string csharp6.Person::get_Name()
23   IL_0014:  stloc.1
24   IL_0015:  nop
25   IL_0016:  ret
26 } // end of method Program::Main
if版的IL

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-14
  • 2022-12-23
  • 2021-07-22
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-29
  • 2022-12-23
  • 2021-10-28
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案