声明中的问号和冒号 [英] Question mark and colon in a statement

查看:115
本文介绍了声明中的问号和冒号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个表达是什么意思



sensor.Quantity =(dr [Quantity]!= DBNull.Value?Convert.ToInt32(dr [Quantity ]):0);



问号和冒号表示什么?

What does this expression means

sensor.Quantity = (dr["Quantity"] != DBNull.Value ? Convert.ToInt32(dr["Quantity"]) : 0);

what the question mark and colon denote?

推荐答案

?:运算符

http://msdn.microsoft.com/en-us/library/ ty67wk28.aspx [ ^ ]



就像速记if-else语句一样。

?: Operator
http://msdn.microsoft.com/en-us/library/ty67wk28.aspx[^]

Like a shorthand if-else statement.
//shorthand
sensor.Quantity = (dr["Quantity"] != DBNull.Value ? Convert.ToInt32(dr["Quantity"]) : 0);

//longhand
if (dr["Quantity"] != DBNull.Value){
    sensor.Quantity = Convert.ToInt32(dr["Quantity"]);
}
else{
    sensor.Quantity = 0;
}


这称为c#条件运算符(?:)或三元运算符。它是一种if-else语句。



This is called c# conditional operator (? : ) or Ternary operator. Its a kind of one line if-else statement.

sensor.Quantity = (dr["Quantity"] != DBNull.Value ? Convert.ToInt32(dr["Quantity"]) : 0);





上述声明验证dr [Quantity]是否为not NULL,和

如果为true则返回dr [Quantity]的值(这是问号部分)。

如果False返回零。 (这是科隆部分)





详情请参阅以下内容。



http://www.codecandle.com/articles/ csharp / operators / conditional-operator-%28ternary-operator%29.html [ ^ ]



http://msdn.microsoft.com/en-us/library/ty67wk28.aspx [ ^ ]



使用C#三元(?)运算符语句作为方法参数 [ ^ ]



http://stackoverflow.com/questions/3312786/benefits-of-using-the-conditional-ternary-运营商 [ ^ ]



The above statement validates whether dr["Quantity"] is not NULL , and
If true return the value of dr["Quantity"] ( This is Question mark section).
If False return zero. ( This is the Colon section)


Please refer below for details.

http://www.codecandle.com/articles/csharp/operators/conditional-operator-%28ternary-operator%29.html[^]

http://msdn.microsoft.com/en-us/library/ty67wk28.aspx[^]

Using C# Ternary (?) Operator Statement as a Method Parameter[^]

http://stackoverflow.com/questions/3312786/benefits-of-using-the-conditional-ternary-operator[^]


它被称为条件运算符: MSDN [ ^ ]这是一个的缩写形式if ... else block。

It's called a conditional operator: MSDN[^] and it's a short form of an if...elseblock.
A = B ? C : D;

相当于:

Is the equivalent of:

if (B)
   A = C;
else
   A = D;

这很有用,但它很难阅读,所以你必须要小心使用它。

如果是这种情况,如果DataReader值在DB中为空,则sensor.Quantity的值为零。否则,它获得实际值。

It's useful, but it can be hard to read, so you have to be careful where you use it.
If your case, if the DataReader value has a null in the DB, then sensor.Quantity gets a value of zero. Otherwise, it gets the actual value.


这篇关于声明中的问号和冒号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆