6

C# 中感叹号(!) 作用盘点

 3 years ago
source link: http://www.cnblogs.com/stulzq/p/14085008.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

1.关系运算符

!= 与等号共同组成关系运算符,检查两个操作数的值是否相等,如: A!=B

2.逻辑运算符

! 称为逻辑非运算符。用来逆转操作数的逻辑状态。如果条件为真则逻辑非运算符将使其为假。如: bool a=true; bool b=!a;

3.null 容忍操作符(null-forgiving operator)

来自于 C#8 的新特性,比较冷门,国内的翻译 C#8 的文章基本都没有提到。它是一个非常有用的特性。

官方文档: ! (null-forgiving) operator (C# reference)

它的主要作用就是告诉编译器,变量不可能为 null,这对于有代码洁癖的人来说非常有用。

me2iYzq.png!mobile

上面的代码, json["name"] 返回的是可空引用类型 JToken? 所以一般需要做是否为空的判断,不然调用 Value<string>() 方法会引起异常。但是在上图的代码中,是不可能为空的,所以要去掉这个波浪线,要么写个 if 判断来取消,要么就使用 !

mmEfInQ.png!mobile

但是注意这个不要乱用,只有确认 一定不会为空 的时候才能使用


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK