加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 多态 – 覆盖和重载

发布时间:2020-12-16 09:37:18 所属栏目:asp.Net 来源:网络整理
导读:为什么重载称为编译时多态性并覆盖调用的运行时多态?例如,看看下面的代码: Public Class Animal Public Overridable Overloads Sub Eat() MsgBox("Animal Eat no arguement") End Sub Public Overridable Sub Drink() MsgBox("Animal drink arguement") En
为什么重载称为编译时多态性并覆盖调用的运行时多态?例如,看看下面的代码:

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

Public Class Horse
    Inherits Animal
    Public Overloads 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
    Public Overloads Overrides Sub Drink()
        MsgBox("Animal drink 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 Animal
        a2 = New Horse
        a1.Eat()
        a2.Eat("Fruit") 'line 6
    End Sub
End Class

第6行将导致编译时错误,因为程序代表.但是,如果我向动物类添加一个Eat(String),那么它将编译.这背后的原因是什么?

以下帖子中的答案还说:“Overloads关键字是可选的,但如果您将其用于一种方法,则必须将其用于该方法的所有重载:”https://stackoverflow.com/questions/1173257/overloads -keyword式-VB网.如果有问题的函数也覆盖,我并不总是发现这种情况.是这样的吗?

我正在寻找一个使用多态性和接口的大型程序.我提供了上面的课程作为例子用于说明目的.

解决方法

Line 6 will cause a compile time error as the program stands. However,
if I add an Eat(String) to the animal class then it will compile. What
is the reasoning behind this?

这是因为Animal类型暴露的签名没有带字符串的Eat版本,直到您修改了基类(Animal)签名.多态性允许您将马称为动物类型,但仅通过动物的签名(除非您将其转换为马类型).因此,如果您有另一种类型的Cat,它继承自Animal,但没有吃(“”),如果VB允许您提到的内容,则会导致编译器错误.

Also the answer in the following post says: “The Overloads keyword is
optional,but if you use it for one method,you must use it for all
overloads of that method

我认为覆盖提供了你找到的解决方法,但不是100%肯定它.我个人根本不使用Overload来节省打字,因为C#不使用它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读