Part1 -> Section1 -> Basic -> 009. The switch statement

     switch พูดง่ายๆคือ ทำหน้าที่เหมือนกันกับ if statement คือการทำงานตามเงื่อนไข แต่ switch จะเน้นในกรณีที่มีเงื่อนไขหลายเงื่อนไข ลองดูจากตัวอย่าง

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int cond = 1;
            switch (cond)
            {
                case 0:
                    Console.WriteLine("Condition zero");
                    break;
                case 1:
                    Console.WriteLine("Condition one");
                    break;
            }

            Console.ReadLine();
        }
    }
}



     จากโค้ดด้านบน การทำงานคือ switch statement รับตัวแปร cond มาและเปรียบเทียบกับ case ทีละ case ทำงานจากบนลงล่าง จะทำงานจนกระทั่งเจอกับ case ที่มีค่าตรงกับ cond แล้วจึงออกจาก statement ด้วยคำสั่ง break;
     cond ในตัวอย่างเราใช้ integer ซึ่ง switch สามารถรับตัวแปรที่เป็น simple type ได้ทั้งหมด (int, string, float, boolean ฯลฯ) เราลองมาดูการใช้งานอีกตัวอย่าง

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Would you like to play football? (yes/maybe/no)");
            string cond = Console.ReadLine();

            switch (cond)
            {
                case "yes":
                case "maybe":
                    Console.WriteLine("Great!");
                    break;
                case "no":
                    Console.WriteLine("Too bad!");
                    break;
                default:
                    Console.WriteLine("Please choose answer in (yes/maybe/no)");
                    break;
            }

            Console.ReadLine();
        }
    }
}

     จากตัวอย่างมึข้อสังเกต คือ
1. case "yes": ไม่มีคำสั่ง break; แสดงว่า หากผู้ใช้ตอบ yes โปรแกรมจะผ่าน case "yes": ลงไปและทำคำสั่งด้านล่าง คือ คำสั่งเดียวกับ case "maybe" คือ ตอบผู้ใช้ด้วยคำว่า Great!
2. default: จะถูกทำก็ต่อเมื่อ ไม่มี case ใดเลยที่ตรงกับเงื่อนไข ซึ่งในที่นี้โปรแกรมจะตอบผู้ใช้ว่าให้เลือกคำตอบในลิสต์ (yes/maybe/no) เท่านั้น ซึ่ง default ไม่บังคับว่าต้องมีจะใช้หรือไม่ก็ได้ (optional)

สอบถามหรือติดตามได้ที่ https://www.facebook.com/learnaspnetmvcjquery

ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

Part2 -> Section1 The Basic -> 003. MVC Folder Structure

Part2 -> Section1 The Basic -> 001. Introduction

Part2 -> Section1 The Basic -> 005. Controller