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
是否有示例或鏈接,我可以查看創建一個像這樣的代理? – 2010-02-26 07:34:03
@Paul Farry:這是一個簡單的代理模式實現:http://en.wikipedia.org/wiki/Proxy_pattern – casperOne 2010-02-26 07:44:07
謝謝我認爲我已經得到了它..我創建了一個接口(IPOSTerminal)和我的普通類現在實現這一點。我還創建了一個實現IPOSTerminal的代理類。代理內的所有屬性只是拋出一個異常,並且mCurrent終端被設置爲代理或真實類,如果它嘗試使用屬性,它只是出錯。但檢查.Current如上所述工作。這是正確的方法嗎? – 2010-02-26 08:45:27