且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#重载方法

更新时间:2023-02-14 18:34:25

名称相同但签名不同的两个方法称为重载方法.即使方法名称相同,编译器也会在编译时根据方法签名识别方法.

Two methods with the same name but different signatures is called overloaded method. At compile time Compiler will identify the method based on the method signature even though the name of the method is same.

void Add(int x, int y)
{
    Console.WriteLine("Add int");
}
void Add(double x, double y)
{
    Console.WriteLine("Add double");
} 

在此,Add(double x,double y)覆盖第一个功能Add(int x,int y)相同名称的不同签名. 如果我们调用Add(4,2),它将调用Add(int x,int y)函数 如果我们调用Add(4.0,2.0),它将调用Add(double x,double y)函数.

Here the Add(double x, double y) overlaods the first fuction Add(int x, int y) same name different signatures. If we call Add(4,2) it will call the Add(int x, int y) function and if we call Add(4.0,2.0) it will call the Add(double x, double y) function.

  1. 相同名称的不同签名.
  2. 不同数量的参数或不同类型的参数或不同顺序的参数.

  1. Same name different signature.
  2. Different number of arguments or Different types of arguments or Different order of arguments.

无法通过更改方法的返回类型来重载方法.因为仅返回值不足以使编译器确定要调用的方法.同样,方法的返回类型也不被认为是方法签名的一部分.

Can't overload method by Changing the return type of the method. Because return value alone is not sufficient for the compiler to figure out which method to call. Also the return type of a method is not considered to be part of a method's signature.

还请注意,outref参数修改了 可以用于区分重载,如下所示:

Also note, the out and ref parameter modifies can be used to differinate to overloads, like so:

void method1(int x);
void method1(out int x);

void method2(char c);
void method2(ref char c);

但是,您不能这样做:

void method(out int x);
void method(ref int x);

由于refout在过载方面没有区别. 并注意以下这样的重载:

As ref and out do not differentiate from one another, in an overload sense. And be careful with overloads like this:

void method(int x) => Console.Writeline(x);
void method(int x, int y = 0) => Console.Writeline(x * y);

这将编译并工作,但是编译器将默认使用具有一个参数的第一个方法,直到您指定了第二个参数,然后它将调用第二个方法.

This will compile and work, but the compiler will default to the first method that has one parameter, until you specify the second parameter, then it will call the second method.