使用方法重载,您将仅使用不同的参数和/或不同的输出来调用“相同的方法”。这使您可以轻松编写具有相同核心功能但具有不同输入参数的方法。例:
public int Sum(int a, int b) { return a + b;}public double Sum (double a, double b) { return a + b;}否则,您将拥有SumInt(…)和SumDouble(…)之类的方法。您还可以使用2个方法,这些方法具有相同的返回类型但输入不同,并且仍然可以轻松使用重载:
public int Sum(int a, int b) { return Sum(a, b, 0);}public int Sum (int a, int b, int c) { return a + b + c;}这样一来,你只有 一个
地方与人的逻辑和所有其他方法只是调用一个方法与所有的逻辑,只能用不同的参数。然后还有构造函数重载。例如,您可以有一个空的构造函数,可以在其中设置一些默认值,也可以有一个构造函数,可以在其中自己设置值:
//Without overloading you'll have to set the properties after instantiating the classpublic MyClass() { this.PropertyOne = "1"; this.PropertyTwo = 2;}//usage:MyClass instance = new MyClass(); //now theproperties are already set to "1" and 2, wheter you like it or not//here you change the valuesinstance.PropertyOne = "...";instance.PropertyTwo = 0;//With constructor overloading you have thispublic MyClass() { this("One", 2);}public MyClass(string propOne, int propTwo) { this.PropertyOne = propOne; this.PropertyTwo = propTwo;}//usage:MyClass instance = new MyClass("MyValue", 1000);//if you call MyClass() the default values STILL will be set :)第二种方式给您更多的可能性,不是吗?而且它使更改代码变得更加容易。希望这可以帮助!



