问题描述
我有一个类,它有两个具有相同名称和不同类型参数的函数,如下所述:
I have a class having two functions with same name and different type of arguments as described below:
Public Class functionOverload
'<--- first function starts here
Public Function Test(ByVal x As Int16, ByVal y As Int16) As Double
Return x * y
End Function
'<--- first function Ends here
'<--- Second function starts here
Public Function Test(ByVal x As Int32, ByVal y As Int32) As Integer
Return x + y
End Function
'<--- Second function ends here
End Class
在我的主模块中,我创建了一个对象这个类并使用不同的参数调用函数:
In my main module i had created an object of this class and call the function using different arguments:
Dim obj As New functionOverload
MsgBox(obj.Test(10, 20)) '<--- will call second function as both the parameters are of type int32
Dim i, j As Int16
i = 10
j = 20
MsgBox(obj.Test(i, j)) '<--- will call First function as both the parameters are of type int16
到目前为止工作正常。我尝试了更多如下:
Up to this works fine as excepted. and i had tried even more as follows:
MsgBox(obj.Test(i, 10)) '<--- will call second function even though their is no matching function
MsgBox(obj.Test(20, j)) '<--- will call second function even though their is no matching function
问题:为什么会这样?函数超载的规则是不同的vb.net
Question : why this is happening? Is the rules for function over loading is different in vb.net
推荐答案
MsgBox(obj.Test(i, 10)) '<--- will call second function even though their is no matching function
MsgBox(obj.Test(20, j)) '<--- will call second function even though their is no matching function
它的工作原理是因为将 Int16
上传到 Int32
是安全的,所以编译器这样做,然后你有一个调用,你传递两个 Int32
s(这是第二个函数)为 10
和 20
将被解释为 Int32
s,除非另有说明。
希望这有帮助,
Fredrik
It works because upcasting an Int16
to an Int32
is safe, so the compiler that do that, and then you have a call where you pass two Int32
s (which is the second function) as the 10
and 20
will be interpreted as Int32
s unless specified.
Hope this helps,
Fredrik
这篇关于函数重载未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!