简体   繁体   English

C# ?。 条件运算符

[英]c# ?. conditional operator

I have a condition 我有病

if (driver?.VistrackId == 555)

it equivalent (in IL code, not C# code): 它等效(在IL代码中,不是C#代码中):

if (driver != null && driver.VistrackId == 555)

right? 对?

Not exactly 不完全是

It's better Since this notation is thread safe 更好,因为这种表示法是线程安全的

See Null-conditional Operators on MSDN . 请参阅MSDN上的空条件运算符

That's correct. 没错 The "?" “?” checks for null, and if it's not null, the "." 检查是否为空,如果不为空,则检查“。” continues the interrogation of the object 继续对物体的讯问

This code generates the following IL 此代码生成以下IL

var driver = new {VistrackId = 1};

if (driver?.VistrackId == 555)
{
    Console.WriteLine("?. operator");
}

IL: IL:

IL_0000:  nop         
IL_0001:  ldc.i4.1    
IL_0002:  newobj      <>f__AnonymousType0<System.Int32>..ctor
IL_0007:  stloc.0     // driver
IL_0008:  ldloc.0     // driver
IL_0009:  brtrue.s    IL_000E
IL_000B:  ldc.i4.0    
IL_000C:  br.s        IL_001B
IL_000E:  ldloc.0     // driver
IL_000F:  call        <>f__AnonymousType0<System.Int32>.get_VistrackId
IL_0014:  ldc.i4      2B 02 00 00 
IL_0019:  ceq         
IL_001B:  stloc.1     
IL_001C:  ldloc.1     
IL_001D:  brfalse.s   IL_002C
IL_001F:  nop         
IL_0020:  ldstr       "?. operator"
IL_0025:  call        System.Console.WriteLine
IL_002A:  nop         
IL_002B:  nop         
IL_002C:  ret    

Code with == null 代码== null

var driver = new {VistrackId = 1};


if (driver != null && driver.VistrackId == 555)
{
    Console.WriteLine("== null");
}

IL 白介素

IL_0000:  nop         
IL_0001:  ldc.i4.1    
IL_0002:  newobj      <>f__AnonymousType0<System.Int32>..ctor
IL_0007:  stloc.0     // driver
IL_0008:  ldloc.0     // driver
IL_0009:  brfalse.s   IL_001A
IL_000B:  ldloc.0     // driver
IL_000C:  callvirt    <>f__AnonymousType0<System.Int32>.get_VistrackId
IL_0011:  ldc.i4      2B 02 00 00 
IL_0016:  ceq         
IL_0018:  br.s        IL_001B
IL_001A:  ldc.i4.0    
IL_001B:  stloc.1     
IL_001C:  ldloc.1     
IL_001D:  brfalse.s   IL_002C
IL_001F:  nop         
IL_0020:  ldstr       "== null"
IL_0025:  call        System.Console.WriteLine
IL_002A:  nop         
IL_002B:  nop         
IL_002C:  ret         

They are slightly different 它们略有不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM