2009-11-01 74 views
0

嗨我正在探索如何實現一些訪客模式,但沒有所有的裝飾訪問方法。 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 

回答

0

當您將類設置爲Option Strict Off時,您告訴編譯器允許在該類上進行後期綁定,這很可能不是一個好主意。

你應該做的就是將它改爲Option Strict On,這樣你就會得到編譯錯誤,隨後你將停止獲取運行時異常,因爲它會捕獲不正確的參數。

0

車削Option Strict off允許您進行遲到的呼叫Accept(o)

乾淨的解決方案 - 它也解決了您的運行時錯誤問題 - 將打開Option Strict並手動執行後期綁定的呼叫。所以,基本上,你將取代

Public Sub AcceptShape(s as Shape) 
    AcceptAny(s) 
End Sub 
Private Sub AcceptAny(o as Object) 
    Accept(o) 
End Sub 

Public Sub AcceptShape(s as Shape) 
    GetType(ShapeAcceptor).InvokeMember("Accept", BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.InvokeMethod, Nothing, Me, new Object() {s}) 
End Sub 

(見Type.InvokeMember獲取細節。你需要Imports System.ReflectionBindingFlags。)

這基本上做同樣的你的Accept(o)做了什麼,除了它是「Option Strict」兼容的。