Console App รับ Arguments

1.การรับพารามิเตอร์
2.การเปลี่ยนชนิดข้อมูล (casting)

1.การรับอาร์กิวเมนต์

How to: Display Command Line Arguments (C# Programming Guide)

การรับอาร์กิวเมนต์ที่ส่งมาจาก Command Line จะรับเข้ามที่ตัวแปร args

โดยจำนวนอาร์กิวเมนต์จะเท่ากับ args.Length และอาร์กิวเมนต์ตัวแรกคือ args[0]

using System;

namespace Hello
{
    class Program
    {
        static void Main(string[] args)
        {
            // The Length property provides the number of array elements
            Console.WriteLine("parameter count = {0}", args.Length);

            for (int i = 0; i < args.Length; i++)
            {
                Console.WriteLine("Arg[{0}] = {1}", i, args[i]);
            }
        }
    }
}

ทดลองรันโดยใส่ jack และ tip
จะได้ jack เป็นอาร์กิวเมนต์ตัวแรก (args[0])

> dotnet run jack tip
parameter count = 2
Arg[0] = jack
Arg[1] = tip

How to: Access Command-Line Arguments Using foreach (C# Programming Guide)

การแสดงอาร์กิวเมนต์โดยใช้ foreach

using System;

namespace Hello
{
    class Program
    {
        static void Main(string[] args)
        {
            // The Length property provides the number of array elements
            Console.WriteLine("parameter count = {0}", args.Length);

            foreach (string s in args)
            {
                Console.WriteLine(s);
            }
        }
    }
}
> dotnet run jack tip
parameter count = 2
jack
tip

2.การเปลี่ยนชนิดข้อมูล (casting)

Command-Line Arguments (C# Programming Guide)

การเปลี่ยนชนิดข้อมูลด้วย Parse
long num = Int64.Parse(args[0]);
หรือเปลี่ยนชนิดข้อมูลด้วย  Convert
long num = Convert.ToInt64(s);

using System;

namespace Hello
{
    class Program
    {
        static void Main(string[] args)
        {
            // Test if input arguments were supplied:
            if (args.Length == 0)
            {
                Console.WriteLine("Please enter a numeric argument.");
                Console.WriteLine("Usage: Double <num>");
                return;
            }

            // Try to convert the input arguments to numbers. This will throw
            // an exception if the argument is not a number.
            // num = int.Parse(args[0]);
            int num;
            bool test = int.TryParse(args[0], out num);
            if (test == false)
            {
                Console.WriteLine("Please enter a numeric argument.");
                Console.WriteLine("Usage: Double <num>");
                return;
            }

            Console.WriteLine("Double of {0} is {1}.", num, num * 2);
        }
    }
}

ใช้ int.TryParse() ช่วยตรวจสอบว่าเปลี่ยนชนิดข้อมูลสำเร็จหรือไม่

> dotnet run 5
Double of 5 is 10.

Leave a Reply