Dim col As Color 'the color I check
Dim ref As Byte 'the color what I expect
Select Case col.R
Case ref
'code
Case ref - 3 To ref + 3
'code
Case ref - 6 To ref + 6
'code
Case ref - 10 To ref + 10
'code
Case Else
'code
End Select
参考 - X 可以是 < 0 (error) or ref + X can be >255(错误)。
有没有一种快速方法可以避免错误而无需大量 If...then...else?
将字节转换为
Integer
进行比较以避免溢出:
Dim col As Color 'the color I check
Dim ref As Byte 'the color what I expect
Dim intRef As Integer = CInt(ref)
Select Case CInt(col.R)
Case intRef
'code
Case intRef - 3 To intRef + 3
'code
Case intRef - 6 To intRef + 6
'code
Case intRef - 10 To intRef + 10
'code
Case Else
'code
End Select
请注意,两个
CInt()
类型转换都是多余的,可以删除。我只是添加它们以使意图更清晰。由于 intRef
输入为 Integer
,因此字节将自动转换为 Integer
。 扩大转换是隐式完成的,即使使用Option Strict On
。
或更简单
Select Case Math.Abs(CInt(col.R) - ref)
Case 0
'code
Case <= 3
'code
Case <= 6
'code
Case <= 10
'code
Case Else
'code
End Select
由于
CInt(col.R)
是 Integer
,因此 ref
将自动扩展为 Integer
进行减法。