Computer >> Máy Tính >  >> Lập trình >> C#

Nạp chồng phương thức trong C # là gì?

Hai hoặc nhiều hơn hai phương thức có cùng tên nhưng khác tham số là những gì chúng ta gọi là nạp chồng phương thức trong C #.

Việc nạp chồng phương thức trong C # có thể được thực hiện bằng cách thay đổi số lượng đối số và kiểu dữ liệu của đối số.

Giả sử bạn có một hàm in phép nhân các số, khi đó các phương thức nạp chồng của chúng ta sẽ có cùng tên nhưng khác số đối 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) { }

Sau đây là một ví dụ cho thấy cách triển khai nạp chồng phương thức -

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));
   }
}

Đầu ra

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