要求业务验证的情况大致可以分为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 Sub
End Class
Class 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 Sub
End 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