C# 工作中提高编码效率的运算符

来源:互联网 发布:淘宝售后客服好做吗 编辑:程序博客网 时间:2024/06/05 04:50

 工作中提高效率的运算符

1 ?: 运算符

条件运算符 (?:) 根据Boolean 表达式的值返回两个值之一。

x != 0.0 ? Math.Sin(x) / x : 1.0;

代替

if(x!=0.0){...}else{...}

 

2  ?? 运算符

?? 运算符称为 null 合并运算符,用于定义可以为 null 值的类型和引用类型的默认值。如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。

 int y = x ?? -1;

代替

if(x!=null){...}else{...}


3 => 运算符

=> 标记称作 lambda 运算符。该标记在 lambda 表达式中用来将左侧的输入变量与右侧的 lambda 体分离。Lambda 表达式是与匿名方法类似的内联表达式,但更加灵活;在以方法语法表示的 LINQ 查询中广泛使用了 Lambda 表达式。

int[ ] output = Array.ConvertAll( input, s => int.Parse( s ) );

代替

int[ ] output = Array.ConvertAll<string, int>( input, delegate( string s ) { return int.Parse( s ); } );

主要是代替delegate

以上是本人工作中经常使用的提高编码效率的运算符。
原创粉丝点击