Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Nạp chồng (Overloading) trong C# là gì?

C# cung cấp hai kỹ thuật triển khai đa hình tĩnh:

  • Nạp chồng hàm (Function overloading)
  • Nạp chồng toán tử (Operator overloading)

Nạp chồng hàm (Function Overloading)

Hai hoặc nhiều phương thức cùng tên nhưng tham số khác nhau gọi là function overloading trong C#.

Function overloading thực hiện bằng cách thay đổi số lượng tham số và/hoặc kiểu dữ liệu tham số.

Giả sử hàm in tích của các số, các phương thức nạp chồng cùng tên nhưng khác số tham số:

public static int mulDisplay(int one, int two) { } 
public static int mulDisplay(int one, int two, int three) { } 
public static int mulDisplay(int one, int two, int three, int four) { }

Ví dụ triển khai function overloading:

Ví dụ

using System; 
public class Demo { 
    public static int mulDisplay(int one, int two) { 
        return one * two; 
    } 
    public static int mulDisplay(int one, int two, int three) { 
        return one * two * three; 
    } 
    public static int mulDisplay(int one, int two, int three, int four) { 
        return one * two * three * four; 
    } 
} 
public class Program { 
    public static void Main() { 
        Console.WriteLine("Multiplication of two numbers: " + Demo.mulDisplay(10, 15)); 
        Console.WriteLine("Multiplication of three numbers: " + Demo.mulDisplay(8, 13, 20)); 
        Console.WriteLine("Multiplication of four numbers: " + Demo.mulDisplay(3, 7, 10, 7)); 
    } 
}

Kết quả

Multiplication of two numbers: 150
Multiplication of three numbers: 2080
Multiplication of four numbers: 1470

Nạp chồng toán tử (Operator Overloading)

Toán tử nạp chồng là hàm với tên đặc biệt: từ khóa operator theo sau bởi ký hiệu toán tử được định nghĩa.

Bảng sau cho biết toán tử nào có thể nạp chồng, nào không:

STTToán tử & Mô tả
1+, -, !, ~, ++, --
Toán tử một ngôi (unary), một toán hạng, có thể nạp chồng.
2+, -, *, /, %
Toán tử hai ngôi (binary), hai toán hạng, có thể nạp chồng.
3==, !=, <, >, <=, >=
Toán tử so sánh có thể nạp chồng.
4&&, ||
Toán tử logic điều kiện KHÔNG thể nạp chồng trực tiếp.
5+=, -=, *=, /=, %=
Toán tử gán KHÔNG thể nạp chồng.
6=, ., ?:, ->, new, is, sizeof, typeof
Các toán tử này KHÔNG thể nạp chồng.