c#中“!”和“!”有什么区别 运算符和“?” 操作员?

Alp*_*Alp -2 c# null nullable

这些运算符有什么区别?

var c = foo?.Prop1;
Run Code Online (Sandbox Code Playgroud)
var c = foo!.Prop1;
Run Code Online (Sandbox Code Playgroud)

顺便说一句,Prop1是一个int.

Dmi*_*nko 6

?is null宽容运算符时,null 是!有条件的:

  • ?. 如果是什么full都不null做(或返回null
  • !. 不要相信这种情况foo会发生null并停止警告我。

所以如果foonull

var c = foo?.Prop1; // c will be null (c will be of type int?)
var d = foo!.Prop1; // exception will be thrown (d is int)
Run Code Online (Sandbox Code Playgroud)