我正在尝试使用接口实现策略设计模式。 然而,在开发一些代码时,我偶然发现了一些奇怪的东西。 在设计时未验证对象的类型。
请注意以下代码。 请注意,Foo实现IFoo,Bar不实现此接口。 尝试此操作时不会显示错误:
Dim fb2 As FooBar = New FooBar(bar)
完整代码:
Module Module1
Sub Main()
Try
Dim foo As Foo = New Foo()
Dim bar As Bar = New Bar()
Dim fb1 As FooBar = New FooBar(foo)
fb1.DoIt()
Dim fb2 As FooBar = New FooBar(bar)
fb2.DoIt()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
End Sub
End Module
Public Class FooBar
Private _f As IFoo
Public Sub New(ByVal f As IFoo)
_f = f
End Sub
Public Sub DoIt()
_f.DoSomething()
End Sub
End Class
Public Interface IFoo
Sub DoSomething()
End Interface
Public Class Foo
Implements IFoo
Public Sub DoSomething() Implements IFoo.DoSomething
Console.WriteLine("DoSomething() called in Foo")
End Sub
End Class
Public Class Bar
Public Sub DoSomething()
Console.WriteLine("DoSomething() called in Bar")
End Sub
End Class
此代码编译良好。 Visual Studio中未显示任何错误。 但是,当我运行这段代码时,我收到一个InvalidCastException。 控制台的输出:
DoSomething() called in Foo
Unable to cast object of type 'InterfaceTest.Bar' to type 'InterfaceTest.IFoo'.
任何人都可以解释这种行为吗?