要求業務驗證的情況大致可以分為3類
1、某一個值本身需要驗證
2、僅當另外一個值出現時,某一個值需要驗證
3、僅當另外一個資料集裡麵包含的某一個資料滿足某個條件時,某一個值需要驗證
商務邏輯的驗證要求驗證方法集中處理,盡量避免在整個系統中對同一個值存在多個業務驗證。
驗證:返回true或false的方法,該方法必須包含兩個參數,1、驗證資料本身;2、驗證資料的處理方法
驗證中必須理解的技術:
delegate:表示委託,委託是一種資料結構,它引用靜態方法或引用類執行個體及該類的執行個體方法。要求被引用方法的參數和傳回值和delegate聲明的方法一致的類。該類的方法就可以被delegate類型調用。
一下為兩個例子:
例子一:
Public Class SamplesDelegate
' 為一個方法申明委託
Delegate Function myMethodDelegate(myInt As Integer) As [String]
' 申明委託能夠指向的方法
Public Class mySampleClass
' 定義需要執行個體化的方法.
Public Function myStringMethod(myInt As Integer) As [String]
If myInt > 0 Then
Return "positive"
End If
If myInt < 0 Then
Return "negative"
End If
Return "zero"
End Function 'myStringMethod
' 定義靜態方法
Public Shared Function mySignMethod(myInt As Integer) As [String]
If myInt > 0 Then
Return "+"
End If
If myInt < 0 Then
Return "-"
End If
Return ""
End Function 'mySignMethod
End Class 'mySampleClass
Public Shared Sub Main()
' 為每個方法申明一個委託myD1,myD2.
Dim mySC As New mySampleClass()
Dim myD1 As New myMethodDelegate(AddressOf mySC.myStringMethod)'引用執行個體方法
Dim myD2 As New myMethodDelegate(AddressOf mySampleClass.mySignMethod)'引用靜態方法
' 通過委託調用.
Console.WriteLine("{0} is {1}; use the sign ""{2}"".", 5, myD1(5), myD2(5))
Console.WriteLine("{0} is {1}; use the sign ""{2}"".", - 3, myD1(- 3), myD2(- 3))
Console.WriteLine("{0} is {1}; use the sign ""{2}"".", 0, myD1(0), myD2(0))
End Sub 'Main
End Class 'SamplesDelegate
例子二:
Public Class SortClass
'聲明委託 Delegate
Function Compare(ByVal x As Integer, _ ByVal y As Integer) As Boolean '申明委託指向的執行個體方法
Function CompareValues(ByVal X As Integer, _ ByVal Y As Integer) As Boolean If X > Y Then CompareValues = True Else CompareValues = False End If End Function '聲明使用委託的方法
Sub SelectionSort(ByVal IsGreaterThan As Compare, _ ByVal IntArray() As Integer) Dim MaxVal As Integer Dim MaxIndex As Integer Dim i, j As Integer ' Step through the elements in the array starting with the ' last element in the array. For i = UBound(IntArray) To 1 Step -1 MaxVal = IntArray(i) MaxIndex = i For j = 1 To i ' 使用委託. If IsGreaterThan.Invoke(IntArray(j), MaxVal) Then MaxVal = IntArray(j) MaxIndex = j End If Next j ' 使用委託. If IsGreaterThan.Invoke(i, MaxIndex) Then IntArray(MaxIndex) = IntArray(i) IntArray(i) = MaxVal End If Next i End SubEnd ClassClass Class1 Sub SortArray()
'聲明被委託指向的執行個體化對象 Dim Sort As New SortClass() Dim arr1() As Integer = {1, 5, 3, 2, 7, 22, 5, 54, 12} Sort.SelectionSort(AddressOf Sort.CompareValues, arr1) MsgBox("Array sorted.") End SubEnd Class '測試
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click Dim c As New Class1() c.SortArray() End Sub