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

C# 方法多載完全指南:建構子多載、參數解析規則與 Console.WriteLine 實例

     編輯:關於C#

方法多載核心概念

同一類別中定義同名但參數簽章不同的多個方法。編譯器在編譯期根據呼叫端提供的實際引數型別、數量、順序進行靜態綁定,選擇最佳匹配。

建構子多載範例:Vehicle 類別


public class Vehicle {
    public int Wheels { get; set; }
    public float Weight { get; set; }

    // 無參數建構子:使用預設值
    public Vehicle() : this(4, 1500f) { }

    // 兩參數建構子:完整初始化
    public Vehicle(int wheels, float weight) {
        Wheels = wheels;
        Weight = weight;
    }

    public void Show() => Console.WriteLine($"Wheels: {Wheels}, Weight: {Weight}kg");
}

// 使用
var v1 = new Vehicle();           // 呼叫無參數版
var v2 = new Vehicle(2, 200f);    // 呼叫兩參數版

一般方法多載:學生比較器


public class Student {
    public string Name { get; }
    public int Age { get; }
    public float Weight { get; }
    public Student(string name, int age, float weight) { Name = name; Age = age; Weight = weight; }

    // 多載:比較整數 (年齡)
    public int Max(int x, int y) => x > y ? x : y;
    // 多載:比較浮點數 (體重)
    public float Max(float x, float y) => x > y ? x : y;
}

// 呼叫端無需記住不同方法名
var s1 = new Student("Mike", 21, 70f);
var s2 = new Student("John", 20, 65f);
Console.WriteLine($"Max Age: {s1.Max(s1.Age, s2.Age)}");
Console.WriteLine($"Max Weight: {s1.Max(s1.Weight, s2.Weight)}");

Console.WriteLine 多載家族 (簡化版)


// 核心多載
WriteLine();
WriteLine(bool value);
WriteLine(char value);
WriteLine(int value);
WriteLine(uint value);
WriteLine(long value);
WriteLine(ulong value);
WriteLine(float value);
WriteLine(double value);
WriteLine(decimal value);
WriteLine(string value);
WriteLine(object value);
WriteLine(char[] buffer);
WriteLine(string format, object arg0);
WriteLine(string format, object arg0, object arg1);
WriteLine(string format, object arg0, object arg1, object arg2);
WriteLine(string format, params object[] args);
// 共 19 個公開多載 (實際更多)

多載解析規則 (簡化版)

  1. 適用性:引數可隱式轉換為參數型別。
  2. 優越性:至少有一個引數轉換「更好」(如 int 優於 long),且無任何引數轉換「更差」。
  3. 唯一性:恰好有一個最佳候選,否則編譯錯誤 CS0121 (模糊呼叫)。

常見模糊呼叫陷阱


void M(int x) { }
void M(long x) { }
M(5); // OK,選 int 版本 (5 為 int 常值)

void N(object o) { }
void N(string s) { }
N(null); // CS0121:null 同時適用 object 與 string
// 解決:N((string)null) 或 N((object)null)

多載 vs 覆寫 vs 隱藏

機制範圍關鍵字綁定時機目的
多載同一類別無編譯期提供多種參數介面
覆寫衍生類別override執行期多態行為變化
隱藏衍生類別new編譯期替換基類別成員 (非多態)

設計建議

  • 多載方法應語意一致,僅參數形式不同。
  • 避免超過 5-6 個多載,考慮 params、optional parameters、Builder pattern。
  • 公開 API 多載變更屬於中斷性變更,需謹慎規劃版本策略。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved