【发布时间】:2012-01-06 11:18:14
【问题描述】:
我正在尝试使用接口来实现策略设计模式。 然而,在开发一些代码时,我偶然发现了一些奇怪的东西。 对象的类型未在设计时验证。
观察下面的代码。 请注意 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'.
谁能解释这种行为?
【问题讨论】:
-
你应该将Option Strict设为默认!
-
是的...我打字变慢了
-
通过接口传递对象真的是隐式转换吗?设置 option:strict 标识作为接口类型参数传递的所有对象,即使该转换完全有效,可以在设计时进行验证。
标签: vb.net interface design-time