使用具有不兼容签名的多态性

时间:2014-11-22 12:49:09

标签: vb.net design-patterns

假设我有这样的类结构:

Public class Person1
  inherits Person

public function Greeting(ByVal strGreeting As String)
  return strGreeting
end function

end class

Public class Person2
   inherits Person

public function Greeting()
  return "Hello"
end function

end class

我希望能够使用多态来调用:问候,即

dim P1 As Person = New Person1
dim P2 As Person = New Person2

msgbox(P1.Greeting)
msgbox(P2.Greeting)

但是,Person2接受一个参数,因此签名不一样。解决方案是什么?

1 个答案:

答案 0 :(得分:0)

您的person对象是刚刚发生的类型的实例从某些相同的类型继承。作为Person1的一个实例,P1对象不会对Person2中包含的方法有任何了解,因为它是不同的类型。

我不太确定你的目标是什么,但这是构建它的一种方法:

Public MustInherit Class Person
    Public Property Name As String

    Public Sub New(n As String)
        Name = n
    End Sub

    ' "I dont care HOW they do it, but child types 
    '    must provide a Greeting() function"
    MustOverride Function Greeting() As String

    ' overload: takes an arg/different sig
    Public Overridable Function Greeting(strGreeting As String) As String
        Return String.Format("Greetings, {0} {1}", strGreeting, Name)
    End Function

End Class

Public Class Person1
    Inherits Person

    Public Sub New(n As String)
        MyBase.New(n)
    End Sub

    ' override with a specific form of address
    Public Overrides Function Greeting() As String
        Return "Hello, Mr " & Name
    End Function

End Class

Public Class Person2
    Inherits Person

    Public Sub New(n As String)
        MyBase.New(n)
    End Sub

    Public Overrides Function Greeting() As String
        Return "Hello, Senorita " & Name
    End Function

End Class

然后:

Dim Pa1 As New Person1("Ziggy")
Dim Pa2 As New Person2("Zoey")

Console.WriteLine(Pa1.Greeting)
Console.WriteLine(Pa2.Greeting("Ms"))   ' uses base class overload
Console.WriteLine(Pa2.Greeting())

输出:

Hello, Mr Ziggy                ' from P1
Greetings, Ms Zoey             ' from base class
Hello, Senorita Zoey           ' from P2 

基类更常见的是为所有继承的类型定义一个默认的Greeting,然后一些基类可能会覆盖它而另一些不依赖于所需的类。