C# 中的方法重载是什么?

csharpprogrammingserver side programming更新于 2025/10/14 20:37:17

在 C# 中,两个或两个以上具有相同名称但不同参数的方法被称为方法重载。

C# 中的方法重载可以通过更改参数的数量和参数的数据类型来实现。

假设你有一个打印数字乘法的函数,那么我们重载的方法将具有相同的名称,但参数数量不同 −

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

以下示例展示了如何实现方法重载 −

示例

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

输出

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

相关文章