2012年10月11日 星期四

第一步 HelloWorld

我個人認為Microsoft的開發環境畢竟比較友善,所以建議初學者安裝Visual Studio系列產品,不過如果有其他熟悉的IDE也可以,畢竟要跟大家分享的是語言不是工具..^^

有了開發環境之後,我們開始新增一個【主控台應用程式】專案吧!
在工具列上面找到【檔案】==>【新增】==>【專案】==>【Visual C#】==>【Windows】==> 【主控台應用程式】。

這時候會看到IDE自動幫你產生的程式碼如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

接下來在【Main】大括弧之中敲入第一行的程式碼,讓程式大聲說HelloWorld吧

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("HelloWorld");
        }
    }
}

在看到期待已久的結果前,我們必須要先編譯剛剛寫的程式碼,怎麼編譯呢?
在工具列上面找到【建置】==>【建置方案】

程式碼編譯完成了,要怎麼看到結果呢?
在工具列上面找到【偵錯】==>【開始偵錯】

見鬼了,好像看到有一個黑底的視窗一閃而逝,發生什麼事情??
原因是【程式執行完就關閉了】所以看到黑底視窗一閃而逝,怎麼讓程式停住,好讓我們看一下結果呢?? 要在原本的程式碼中再加入一行程式碼

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("HelloWorld");
            Console.ReadKey();
        }
    }
}

修改完程式碼記得要重新編譯一下,執行【開始偵錯】,是不是看到結果了??
接著的問題是,看完結果了要怎麼結束??答案是在鍵盤上按下【任意鍵】..^^

回頭來解釋一下我們添加的兩行程式碼

Console.Write("HelloWorld");

上面這行程式碼的用途,在於讓程式將文字【顯示】在【命令提示字元視窗】

Console.ReadKey();

而上面這行程式碼的用途,在於讓程式【擷取使用者按下鍵盤的哪一個按鍵】,所以當程式開始執行,而你沒有按下任何鍵盤上的按鍵,程式就停住並持續等待,直到你按下任何一個按鍵,接著程式碼繼續往下執行就結束了,今天就先到這,明天見。

沒有留言:

張貼留言