2010-02-26 26 views
1

我想在一些代碼中設置一些修復程序,這些代碼已經引起我的注意,並且試圖獲取一些異常以便在開發人員嘗試訪問屬性時吐出規則沒有得到滿足。如果開發人員使用屬性時強制執行異常

nb。 Clarity省略了許多這類課程。

myobject = new POSTerminalList(mCommonManagers) 

' This should throw an error which it does but is out of scope. 
Log.Write(myobject.Current.Description) 

目前我正在拋出一個異常,但是這會失去調用函數(這真的是存在問題的地方)。

有沒有某種方法來保護這樣的屬性,以便如果開發人員錯誤地使用該屬性,那麼您知道在哪裏尋找而不是在這個類中。

儘管這段代碼是VB.Net我對設計方法感興趣,而不是語言,所以C#實現也適用於我。

<DebuggerDisplay("{mCode}", Name:="{mDescription}")> _ 
Public Class POSTerminalList 
Inherits SortedList(Of Integer, POSTerminal) 

    Private mCurrentTerminal As POSTerminal 
    Private mCurrentTerminalNumber As Integer 

    Private Sub New() 
     mFullList = New SortedList(Of Integer, POSTerminal) 
    End Sub 

    Public Sub New(ByVal theManagers As IPSBusiness.CommonManagers) 
     Me.New() 
    End Sub 

    ''Internal thread that is assessing things and calling this method. 
    Private Sub SetCurrentTerminal() 
     If mCurrentTerminalNumber = 0 Then 
      mCurrentTerminal = Nothing 
     Else 
      If Me.ContainsKey(mCurrentTerminalNumber) Then 
       mCurrentTerminal = me.Item(mCurrentTerminalNumber) 
      Else 
       mCurrentTerminal = Nothing 
      End If 
     End If 
    End Sub 

    Public ReadOnly Property Current() As POSTerminal 
     Get 
      If mCurrentTerminal Is Nothing Then 
       Throw New POSTerminalMissingException(
        "Attempt to use the Current Terminal without a " + 
        "valid current terminal. This is a developer error.") 
      Return mCurrentTerminal 
     End Get 
    End Property 

End Class 

回答

2

首先,我建議您不要通過Description屬性拋出異常。雖然你認爲它超出了範圍,但它確實是當前屬性失敗的原因,並且通過通過Description屬性公開,最終導致代碼的使用者錯誤地認爲其他東西是錯誤的。這就是說,如果你真的想這樣做,你應該基本上向POSTTer​​minal類公開代理,其中屬性委託調用Current公開的POSTTer​​minal實例上的相同屬性。這樣,當代理的屬性被調用時,如果它們失敗,調用堆棧將通過代理上的屬性運行。

+0

是否有示例或鏈接,我可以查看創建一個像這樣的代理? – 2010-02-26 07:34:03

+0

@Paul Farry:這是一個簡單的代理模式實現:http://en.wikipedia.org/wiki/Proxy_pattern – casperOne 2010-02-26 07:44:07

+0

謝謝我認爲我已經得到了它..我創建了一個接口(IPOSTerminal)和我的普通類現在實現這一點。我還創建了一個實現IPOSTerminal的代理類。代理內的所有屬性只是拋出一個異常,並且mCurrent終端被設置爲代理或真實類,如果它嘗試使用屬性,它只是出錯。但檢查.Current如上所述工作。這是正確的方法嗎? – 2010-02-26 08:45:27

相關問題