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
Ref - X 可以 < 0(错误),或者 ref + X 可以 >255(错误)。
有没有一种快速方法可以避免错误而无需大量 If...then...else?
将字节转换为
Integer
进行比较以避免溢出:请注意,这两个
CInt()
强制转换都是多余的,可以删除。我只是添加它们以使意图更清晰。由于intRef
输入为Integer
,字节将自动转换为Integer
。扩大转换是隐式完成的,即使使用Option Strict On
.或者更简单
由于
CInt(col.R)
是Integer
,ref
将自动扩展为Integer
进行减法。