C#需要对一行代码进行一些解释 [英] C# need some explanation about one line of code

查看:90
本文介绍了C#需要对一行代码进行一些解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在使用VisualStudio Windows Froms在C#中执行一个代码,我的问题是:

我有这行代码

 buttonConnect.BackColor = Check.IsConnected? Color.Red:Color.Green; 





我的问题是什么是

 x? x:x; 





我尝试过:



我的意思是,如果还有其中一个,那就是这个吗?有什么不同?或者像一个bool if true color.red if false color.green?

解决方案

它被称为三元运营商 [ ^ ]



[ buttonConnect.BackColor = Check.IsConnected?的等价句法? Color.Red:Color.Green; ]





 < span class =code-keyword> if (Check.IsConnected)
buttonConnect.BackColor = Color.Red;
else
buttonConnect.BackColor = Color.Green;





  var 结果= x? y:z; 
// x是应返回布尔值的条件
=代码注释> 注释> // z将被分配给结果,如果x为假







请参阅此?:运算符(C#参考) [ ^ ]


这是的缩写形式,如果

 < span class =code-keyword> if (Check.Isconnected)
{
buttonConnect.BackColor = Color.Red;
}
else
{
buttonConnect.BackColor = Color.Green;
}



见这里:?:运营商(C#参考) [ ^ ]


它只是一个三元运算符,几乎所有语言都有。



你可以谷歌更多。



从外行人的角度来看,部分



之前的?是条件



之后?

第一部分:如果条件返回TRUE

第二部分(在:之后):如果它返回FLASE或DEFAUlt值

Hello, im doing one code in C# using VisualStudio Windows Froms, and my question is:
I have this line of code

buttonConnect.BackColor = Check.IsConnected ? Color.Red : Color.Green;



And my question is what is

x ? x : x ;



What I have tried:

I mean it's the same of this of have one if and else? what is the diference? or like one bool if true color.red if false color.green?

解决方案

it is called as Ternary Operator[^]

equavalent syntax of [buttonConnect.BackColor = Check.IsConnected ? Color.Red : Color.Green;]
is

if (Check.IsConnected)
      buttonConnect.BackColor = Color.Red;
  else
      buttonConnect.BackColor = Color.Green;



var result = x ? y : z;
// x is the condition which should return a boolean value
// y will be assigned to result, if x is true
// z will be assigned to result, if x is false




refer this ?: Operator (C# Reference)[^]


It's a short form of if:

if (Check.Isconnected)
   {
   buttonConnect.BackColor = Color.Red;
   }
else
   {
   buttonConnect.BackColor = Color.Green;
   }


See here: ?: Operator (C# Reference)[^]


Its simply a ternary operator which is there in almost all languages.

You can google more on that.

From a layman's point of view, the portion

before "?" is the condition

after "?"
1st part: if that condition returns TRUE
2nd part(after ":"): if it returns FLASE or DEFAUlt value


这篇关于C#需要对一行代码进行一些解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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