0

我来自 Java 背景。请看一下下面的代码(示例取自我曾经读过的一本 Java 书籍并将代码转换为 .NET):

Public Class Animal
    Public Overridable Sub Eat()
        MsgBox("Animal Eat no arguement")
    End Sub
End Class

Public Class Horse
    Inherits Animal
    Public Overrides Sub Eat()
        MsgBox("Horse Eat no arguement")
    End Sub
    Public Overloads Sub Eat(ByVal food As String)
        MsgBox("Horse Eat food arguement")
    End Sub
End Class

Public Class Form1

    Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim a1 As New Animal
        Dim a2 As New Horse
        a1.Eat()
        a2.Eat() 
        a2.Eat("Fruit") 'line 5
    End Sub
End Class

我希望 form_load 的第 5 行会产生编译时错误。在 Java 中,编译器会查看引用并看到 Animal 没有采用 String 的 Eat 方法。为什么 .NET 中没有编译错误?

更新 上面的代码有错误。正如回答者指出的那样;a2 是对 Horse 的引用和实例。因此,为什么第 5 行不会导致编译时错误。如果 a2 引用了动物并创建了马的实例,则会出现编译时错误(与 Java 一致)

4

2 回答 2

2

a2 is a reference to a Horse. Horse has an Eat method that takes a string. Now if line 5 was referencing a1, that would result in a compiler error.

于 2012-07-22T21:14:21.357 回答
1

You are overloading eat() with a version that accepts a string arg in the horse class. That is entirely valid.

An overload is a method with the same name but different arguments. Your overloaded eat(string) is perfectly valid and works just fine when called on an object and reference of type horse.

You could not call it on an object or reference of type animal, though.

于 2012-07-22T21:15:20.397 回答