I am trying to understand a basic thing regarding Method Overloading
If a class has two methods overloaded like below:
Add(int a,int b);
and
Add(double i, double y);
And in Main
method if I call the method like below:
Add(2, 3);
Then always the method with integer parameters gets called Add(int a,int b)
Why didn't it call the other method Add(double i, double y)
? As double type can also hold values 2, 3
passed from the main method call.
答案 0 :(得分:1)
Because 2 and 3 have type int
, so the overload that has int
arguments fits ideally. If you want to have overload with double
arguments called, you have to pass doubles or floats.
答案 1 :(得分:1)
因为编译器会使用更接近你调用的参数来调用方法。如果你调用add(2,3),两个参数都是整数,它会为你调用add(int,int)。 For more details, read this tutorial.