今天看C#(我用的书籍是《C#入门经典》),看到三元运算符时,一时理解不了,因为书上关于三元运算符篇幅很少,仅仅简单的说『string resultString=(myinteger<10)? "lessthan10" : "Great than or equal 10";』就这些 除此之外并没有完整的例题,我从网上搜索时也没找到有具体的例题。自己捣鼓了一会把完整的代码给拼了出来,如此一来就容易理解的多了;
代码如下;
class="brush:csharp;gutter:true;"> static void Main(string[] args)
{
int myinteger;
Console.WriteLine("Now enter an integer:");
myinteger = Convert.ToInt32(Console.ReadLine());
string resultString=(myinteger<10)? "你输入的数字小于等于10" : "你输入的数字大于10";
Console.WriteLine(resultString);
Console.ReadKey();
}
下面再举一个下简单例子以便于理解,代码如下:
static void Main(string[] args)
{
int x = 20, y = 30;
int z = x + y;
string Result = (z==50) ? "答案为对!" : "答案有误!";
Console.WriteLine(Result);
Console.ReadKey();
}
综体体感觉, 三元运算符是个很实用的知识点。
备注;本人初入C#学习,水平有限,高手勿喷,希望有志趣的朋友一起学习,相互交流;微博@马and康,欢迎互粉交流。
本文由博客园博主makang所有,如需转载请注明出处;