iT邦幫忙

2021 iThome 鐵人賽

DAY 5
0
自我挑戰組

C# 學習之旅系列 第 5

ASP.NET MVC 從入門到放棄 (Day5) -C# 判斷式 迴圈介紹

接著來講講常用的判斷式寫法....
簡單來說以下就是玩攻略遊戲 在選擇選項的邏輯....

單項if寫法

int a = 1;

if (a == 1)//條件成立
{
   Console.Write(a);
}
else//條件不成成立
{
   Console.Write("fail");
}

多項if寫法

int b = 1;
int c = 2;

if (b > c)//條件一成立
{
   Console.Write(b);
}
else if (b == c)//條件二成立
{
   Console.Write(c);
}
else//上述都不成立
{
   Console.Write(c);
}

if簡寫

int aa = b>c ? 1 : 2;  //如果b>c aa= 1 否則 aa=2   ?代表if  :代表else

註解:if簡寫書上比較少特別講解,但實際上用很常用/images/emoticon/emoticon14.gif

switch

int e = 1;
switch (e)
{
case 1://e 等於 1
    Console.WriteLine("1");
    break;
case 2://e 等於 2
    Console.WriteLine("2");
    break;
case 3://e 等於 3
    Console.WriteLine("3");
    break;
default://全部都不符合走這個
    Console.WriteLine("fail");
    break;
}

for 迴圈 寫法

for (int i = 2; i < 10; i++)
{
   for (int j = 1; j < 10; j++)
   {
      Console.WriteLine(i * j);
   }
}

**foreach 寫法 **

int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int i in numbers)
{
   Console.Write("{0} ", i);
}

註解:foreach跟for迴圈差在 foreach 是專門處理集合的迴圈 集合是什麼 我後面會講..../images/emoticon/emoticon19.gif

while 寫法

int n = 0;
while (n < 5) //n 小於5 進去判斷式
{
   Console.Write(n);
   n++;
}

上一篇
ASP.NET MVC 從入門到放棄 (Day4) -C#運算值介紹
下一篇
ASP.NET MVC 從入門到放棄 (Day6) -C#集合、IEnumerable ICollection IList介紹
系列文
C# 學習之旅30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言