嗨我正在探索如何實現一些訪客模式,但沒有所有的裝飾訪問方法。 Sofar我發現我可以在VB.NET中使用Option Strict Off,但它有一些副作用。我有一組Shape類繼承自基類Shape。假設我們有以下類,接受的形狀:嚴格限制VB.NET
Public Class ShapeAcceptor
Public Sub New()
MyBase.New
End Sub
Public Sub AcceptShape(s as Shape)
AcceptAny(s)
End sub
Private Sub AcceptAny(o as Object)
Accept(o)
End sub
Private Sub Accept(byval s as Shape)
Console.writeLine("Shape")
End Sub
Private Sub Accept(byval s as Square)
Console.WriteLine("Square")
End sub
Private Sub Accept(byval s as Circle)
Console.writeLine("Circle")
End Sub
Private Sub Accept(byval s as Triangle)
Console.writeLine("Triangle")
End Sub
End Class
這適用於選項顯式關閉時。然而,調用AcceptShape方法和其他東西的程序會進行編譯,但會產生運行時異常。我們怎樣才能把它變成一個編譯時錯誤?
Public Class Application
Public Shared Sub Main()
Dim acceptor as new ShapeAcceptor
Dim env as new Envelope
For Each s as Shape in env.Items
acceptor.AcceptShape(s)
Next
acceptor.AcceptShape(new NotAShape())
End Sub
End Class