2016-05-13 63 views
1

为了缩短代码,我期待用下面提到的If Else语句来代替三元符号,但我的代码显示错误。三元符号相当于如果在Else语句c#

if (txtMayAmt.Enabled) 
{ 
    txtMayAmt.Text = txtAprilAmt.Text; 
} 
else 
{ 
    txtMayAmt.Text = "0"; 
} 

我这是在显示错误三进制是

((txtMayAmt.Enabled) ? (txtMayAmt.Text = txtAprilAmt.Text) : (txtMayAmt.Text = "0")); 

请代码的建议。

+2

什么是错误?你想'txtMayAmt.Text = txtMayAmt.Enabled? txtAprilAmt.Text:“0”;' – Lee

+2

语法应该看起来像'x = bool_test? true_result:false_result' – Jonesopolis

+0

对不起,迟到的回复。我的网络瘫痪了。我要感谢大家指出我朝着正确的方向。现在,我可以理解我的代码出了什么问题。 –

回答

5

试试这个:

txtMayAmt.Text = txtMayAmt.Enabled ? txtAprilAmt.Text : "0"; 
1

使用此:

txtMayAmt.Text = txtMayAmt.Enabled ? txtAprilAmt.Text : "0"; 
4

ternary operator ?:采用以下模式:

Variable = (Condition) ? (Value If True) : (Value If False) 

所以你的情况,你可以使用下面的等效声明:

// This will set the Text property to match April if enabled, otherwise "0" 
txtMayAmt.Text = txtMayAmt.Enabled ? txtAprilAmt.Text : "0";