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


在 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

更新于: 2020-06-20

2000+ 浏览量

开启你的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.