Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  Asp.net  >  正文 asp.net C#中条件(三元)运算符 (?:)介绍

asp.net C#中条件(三元)运算符 (?:)介绍

发布时间:2017-12-13   编辑:www.jquerycn.cn
jquery中文网为您提供asp.net C#中条件(三元)运算符 (?:)介绍等资源,欢迎您收藏本站,我们将为您提供最新的asp.net C#中条件(三元)运算符 (?:)介绍资源
本文章详细的介绍了关于asp.net C#中条件(三元)运算符 (?:)用法,有需要的朋友可参考本文章。

三元运算符“?:”,语法为:条件表达式?表达式1:表达式2;
该操作首先求出条件表达式的值(bool类型),为true时调用表达式1,为flase时调用表达式2。其逻辑为:“如果为真执行第一个,否则执行第二个。”

语法

test ? expression1 : expression2


test
任何 Boolean 表达式。

expression1
test 为 true 时返回的表达式。可能是逗点表达式。

expression2
test 为 false 时返回的表达式。可能是逗点表达式。


实例

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy9417')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy9417>

a=3>4?3:4;输出为4。
a=3<4?3:4;输出为3。


 

实例

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy8306')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy8306>

int lenth = 10;

string s ;

s = (lenth>16? "jihua.cnblogs.com" : "计划");

Console.WriteLine(s);

其中condition是要计算的Boolean型表达式,true_value是condition为true时返回的值,false_value是condition为false时返回的值。jihua.cnblogs.com


在此例中,如果晚于下午 6 时,则创建一个包含 "Good evening." 的字符串。使用 if...else 语句的等效代码如下:

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy6073')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy6073>

var now = new Date();
var greeting = "Good";
if (now.getHours() > 17)
   greeting = " evening.";
else
   greeting = " day.";


恰当地使用三元运算符,可以使程序非常简洁。

您可能感兴趣的文章:
javascript中的三元条件运算符
Go 语言运算符
PHP三元/三目运算符的使用例子
asp.net C#中条件(三元)运算符 (?:)介绍
PHP的三种类型的运算符
Swift 运算符
c# 三元操作符学习指南
php运算符及运算符优先级-php入门教程(4)
《Go语言四十二章经》第九章 运算符
Php入门教程之PHP 运算符用法说明

[关闭]