方法重载(overload)
- 在同一个类中,定义多个同名的方法,每个方法有不同的参数类型或参数个数,称为方法重载
- 归纳:同一个类,方法名相同,参数不同(个数、类型、顺序),注意是否重载与返回值无关
//不是重载
namespacee Console01
{
internal class Program
{
static void Main(string[] args)
{
}
public static int fn(int a)
{
return a+b;
]
public static double fn(int a)
{
return a+b;
]
}
}
//是重载
namespacee Console01
{
internal class Program
{
static void Main(string[] args)
{
}
public static int fn(int a)
{
return a+b;
]
public static double fn(int a,int b)
{
return a+b;
]
}
}
方法重载与隐式类型转换
- 隐式类型转换:将一个较小的数据类型换成一个较大的数据类型
- 例子里的(10.4,2)中的2就涉及隐式转换
- 这两个方法都可以用,但是选择了2方法的原因是float占4个字节,double占8个字节
class Program
{
static void Main(string[] args)
{
fn(10.4, 2);
Console.ReadLine();
}
public static int fn(double a,double b)
{
Console.WriteLine("1");
return 10;
}
public static int fn(double a,float b)
{
Console.WriteLine("2");
return 10;
}
}