方法重载(Overload)#
来源:
D:\study\C#1\stu0727\多态
方法重载是指在同一个类中,定义多个同名但参数列表不同的方法。编译器根据调用时传入的参数自动选择匹配的重载版本。
重载规则#
| 规则 | 说明 |
|---|---|
| 方法名必须相同 | 否则不算重载 |
| 参数个数可以不同 | 如 Eat() vs Eat(string name) |
| 参数类型可以不同 | 如 Eat(string) vs Eat(int) |
| 返回值类型不同不算重载 | 仅返回值不同会导致编译错误 |
构造函数重载#
class People
{
// 无参构造函数
public People()
{
Console.WriteLine("无参构造函数");
}
// 1 个 string 参数
public People(string a)
{
Console.WriteLine("string 类型的构造函数");
}
// 1 个 int 参数 — 与上面的 string 版本构成重载
public People(int a)
{
Console.WriteLine("int 类型的构造函数");
}
// 2 个 string 参数 — 参数个数不同,构成重载
public People(string a, string b)
{
Console.WriteLine("两个参数的重载");
}
}
调用示例:
new People(); // → "无参构造函数"
new People(":!23"); // → "string 类型的构造函数"
new People(12); // → "int 类型的构造函数"
new People(":!23", "123"); // → "两个参数的重载"
普通方法重载#
class People
{
// 重载 1:无参
public void Eat()
{
Console.WriteLine("吃饭");
}
// 重载 2:1 个 string 参数
public void Eat(string name)
{
Console.WriteLine($"{name}在吃饭");
}
// 重载 3:2 个参数(string + int)
public void Eat(string name, int count)
{
Console.WriteLine($"{name}吃饭,吃了{count}顿饭");
}
// 重载 4:3 个参数(string + int + string)
public void Eat(string name, int count, string food)
{
Console.WriteLine($"{name}吃饭,吃了{count}顿饭,吃的都是{food}");
}
// 重载 5:3 个 int 参数 — 参数类型不同,构成重载
public int Eat(int a, int b, int c)
{
return c;
}
}