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

C# 語言核心語法與物件導向精華筆記(入門必讀)

     編輯:關於C語言

前言

本文彙整 C# 基礎語法、陣列、集合介面、類別設計、運算子多載、屬性、介面等核心知識點,適合初學者建立完整概念地圖,也供資深開發者快速回顧。

一、基礎語法精粹

1. 參數傳遞:out vs ref

// out:呼叫端無需初始化,被呼叫端必須指派
void GetValues(out int a, out int b) { a = 1; b = 2; }

// ref:呼叫端必須初始化,雙向傳遞
void Swap(ref int x, ref int y) { int t = x; x = y; y = t; }

2. using 區塊:確定性釋放資源

using (Font f = new Font("Arial", 10f))
{
    // 區塊結束自動呼叫 f.Dispose()
}

3. 常數與列舉


const int MaxSize = 100;
enum Color { Red = 1, Green = 2, Blue = 4 }
int c = (int)Color.Red; // 顯式轉型取得底層值

4. 基本 I/O


string line = Console.ReadLine();
int num = Convert.ToInt32(line);
double d = double.Parse(textBox.Text);
Application.DoEvents(); // 處理待決訊息(慎用)

二、陣列全方位

1. 一維陣列


int[] a = new int[5];           // 預設值 0
int[] b = new int[] { 1, 2, 3 };
int[] c = { 4, 5, 6 };          // 隱含型別
foreach (int v in c) { ... }
for (int i = 0; i < c.Length; i++) { ... }

2. 多維陣列


int[,] rect = new int[3, 4];              // 矩形陣列
int[,] rect2 = { {1,2}, {3,4}, {5,6} };   // 初始化

int[][] jagged = new int[3][];            // 階梯陣列
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5 };

3. params 參數陣列


void Sum(params int[] values) { ... }
Sum(1, 2, 3, 4); // 呼叫端可直接傳入多個引數

三、集合介面體系

介面關鍵成員用途
IEnumerableGetEnumerator()支援 foreach
IEnumeratorMoveNext(), Current, Reset()迭代器模式核心
IComparableCompareTo(obj)型別內建排序邏輯

ArrayList 常用操作


al.Add(obj);
al.Remove(obj);
al.Clear();
al.Reverse();
al.Sort(); // 需元素實作 IComparable

四、類別設計核心

1. 存取修飾詞


public          // 完全公開
private         // 僅類別內部
protected       // 衍生類別可見
internal        // 同組件可見
protected internal // 衍生類別或同組件

2. 靜態與實例


static int Count;      // 類別層級,必須在類別中初始化
this.Property = value; // 實例參考

3. 繼承與多型


class Base { public virtual void Show() { } }
class Derived : Base { public override void Show() { } }

4. 運算子多載與型別轉換


public struct Roman
{
    public int Value;

    // 隱式轉換:int -> Roman
    public static implicit operator Roman(int v) => new Roman { Value = v };

    // 顯式轉換:float -> Roman
    public static explicit operator Roman(float v) => new Roman { Value = (int)v };

    // 運算子多載
    public static Roman operator +(Roman a, Roman b) => new Roman { Value = a.Value + b.Value };
}

5. 屬性


private int _age;
public int Age
{
    get => _age;
    set => _age = value; // value 為隱含參數
}

五、介面進階

1. 介面實作與測試


interface IA { void Do(); }
class A : IA { public void Do() { } }

// 型別測試
if (obj is IA ia) ia.Do(); // 模式比對 (C# 7+)
IA ia2 = obj as IA;
if (ia2 != null) ia2.Do();

2. 介面繼承與多重實作


interface IAA : IA { float F { get; set; } }
class C : IA, IAA { ... } // 逗號分隔實作多個介面

總結

C# 以強型別、物件導向、垃圾回收為核心,語法簡潔而強大。掌握上述基石,即可輕鬆進階至 LINQ、非同步程式設計、泛型等高階主題。建議配合實際撰寫小專案,將語法內化為肌肉記憶。

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