首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

Visual C# .NET 入門教程:從 Hello World 到 QuickSort 完整實戰

     編輯:關於C#

簡介

Visual C# .NET 是 Visual Studio 系列的新成員,語法基於 C/C++ 並強化組件化編程。本教程通過構建 QuickSort 控制台應用,涵蓋專案建立、控制台 I/O、檔案操作、陣列集合、函數遞迴、除錯技巧等核心技能。

環境需求

  • Visual Studio .NET(Beta 2 或以上)
  • C/C++ 基礎有幫助但非必須

步驟 1:建立專案

  1. 選單 File → New → Project
  2. 選 Visual C# Projects → Console Application
  3. 命名專案與路徑,VS 自動建立目錄

新建專案對話框 選擇專案類型 設定專案名稱

步驟 2:Hello World

修改 Class1.cs:

using System;
namespace quicksort {
    class Class1 {
        static void Main(string[] args) {
            Console.WriteLine("Hello, C#.NET World!");
        }
    }
}

編譯(Build → Build),執行(Debug → Start Without Debugging)。

IntelliSense 提示 編譯輸出 建置選單 啟動除錯 程式輸出

步驟 3:程式結構解析

  • 註解:// 單行,/* */ 多行
  • using 指令:簡化命名空間引用,如 using System; 後可直接用 Console
  • 類別聲明:所有函數必須封裝在類別中
  • Main() 入口:程式啟動點,string[] args 接收命令列參數

步驟 4:控制台輸入

Console.Write("Source: ");
string src = Console.ReadLine();
Console.Write("Output: ");
string dest = Console.ReadLine();

輸入提示畫面

步驟 5:使用 ArrayList 動態陣列

using System.Collections;
ArrayList lines = new ArrayList();
lines.Add("new item");
string s = (string)lines[0]; // 或 lines.Item(0)

步驟 6:檔案讀寫

using System.IO;
// 讀取
FileStream fsIn = new FileStream(src, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fsIn);
while ((line = sr.ReadLine()) != null) lines.Add(line);
sr.Close(); fsIn.Close();

// 寫入(排序後)
FileStream fsOut = new FileStream(dest, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fsOut);
for (int i = 0; i < lines.Count; i++) sw.WriteLine(lines[i]);
sw.Close(); fsOut.Close();

讀取檔案 寫入檔案

步驟 7:QuickSort 遞迴實現

static void QuickSort(ArrayList arr, int low, int high) {
    if (low < high) {
        int pivot = Partition(arr, low, high);
        QuickSort(arr, low, pivot - 1);
        QuickSort(arr, pivot + 1, high);
    }
}

static int Partition(ArrayList arr, int low, int high) {
    string pivot = (string)arr[low];
    int left = low + 1, right = high;
    while (left <= right) {
        while (left <= right && ((string)arr[left]).CompareTo(pivot) <= 0) left++;
        while (left <= right && ((string)arr[right]).CompareTo(pivot) > 0) right--;
        if (left < right) Swap(arr, left++, right--);
    }
    Swap(arr, low, right);
    return right;
}

執行 QuickSort 排序結果

步驟 8:除錯器實戰

  • 設中斷點(右鍵行號 → Insert Breakpoint)
  • 啟動除錯(Debug → Start)
  • Step Over / Step Into 單步執行
  • 滑鼠懸停變數查看值,右鍵 QuickWatch 觀察複雜物件
  • Call Stack、Threads、Memory 等進階工具

設中斷點 除錯中 單步執行 變數提示 QuickWatch

完整原始碼與資源

文末提供完整 QuickSort.cs、專案檔與編譯後可執行檔下載。推薦延伸閱讀:《Inside C#》、《C# How to Program》、《A Programmer's Introduction to C#》、《Introducing Microsoft .NET》。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved