如何将从派生类初始化的对象传递给以Interface作为参数的方法?以下是我正在尝试的例子。可能吗?请建议任何更好的方法。
Public Interface IFruit
Property Name As String
Property Color As String
End Interface
Public Class Fruit
Implements IFruit
Private _Name As String
Private _Color As String
Public Property Color As String Implements IFruit.Color
Get
Return _Color
End Get
Set(value As String)
_Color = value
End Set
End Property
Public Property Name As String Implements IFruit.Name
Get
Return _Name
End Get
Set(value As String)
_Name = value
End Set
End Property
End Class
Public Class FruitExtended
Inherits Fruit
Private _Taste As String
Public Property Taste() As String
Get
Return _Taste
End Get
Set(ByVal value As String)
_Taste = value
End Set
End Property
End Class
Public Class A
Public Sub ProcessFruit(F as IFruit)
'...
'Do something
End Sub
下面的代码会起作用吗?或者如何以其他方式实现这一目标?
Public Sub Test()
Dim F1 as new FruitExtended()
ProcessFruit(F1)
End sub
End Class
答案 0 :(得分:0)
我没有尝试你的代码,但是 - 通常 - 接口很好,因为它们定义了行为而不是状态(属性)。所以也许你可以重新考虑你的设计并问自己ProcessFruit应该用IFruit做什么。
有些语言甚至不允许在接口中声明属性,而不是常量。 Java就是一个例子。