本文主要介紹C#如何處理從Command line帶進來的變數值,以供有興趣的朋友參考。



using System;
using System.Collections.Generic;
using System.Text;

namespace CmdLineInput
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("You entered the following {0} command line arguments:", args.Length);

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

Output:
You entered the following 4 command line arguments:
A
B
C
D

說明:
1. 不像 C 和 C++,程式名稱不會當做第一個命令列引數處理。
2. 使用 for 迴圈, 將帶入的參數逐一顯示在 console 上.

另一種方式, 使用 foreach statement

using System;
using System.Collections.Generic;
using System.Text;

namespace CmdLineArgus
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("You entered the following {0} command line arguments:", args.Length);

            foreach (string s in args)
            {
                Console.WriteLine("{0}", s);
            }
        }
    }
}

說明:
1. foreach 提供了一個簡單且清楚的方法來逐一查看陣列中的元素.


* 用 console mode 啟動測式應該都很OK, 但大部分都是殺雞用牛刀, 使用Visual Studio編輯器請照下面步驟:
Project -> 專案名稱的 Properties -> Debug -> Start Option -> Command line arguments
然後輸入程式啟始時想帶入的參數, 如 A B C D

arrow
arrow
    文章標籤
    C# Command Line Arguments
    全站熱搜

    mark528 發表在 痞客邦 留言(0) 人氣()