我正在使用以下函数来增亮颜色值(它是我的代码中的 lambda,但这不应该产生差异):

Function ReduceDistanceTo255(ByVal i As Byte) As Byte
    Return i + (255 - i) \ 2
End Function

它不会编译,因为编译器会解释 2552 作为整数而不是字节,使得结果为 type Integer. 。很遗憾, 没有 Byte 类型字符, ,所以我不能只写 255B 或类似的东西。

该问题有一些明显的解决方法:

Function ReduceDistanceTo255(ByVal i As Byte) As Byte
    Return i + (CByte(255) - i) \ CByte(2)
End Function

Function ReduceDistanceTo255(ByVal i As Byte) As Byte
    Return CByte(i + (255 - i) \ 2)
End Function

Function ReduceDistanceTo255(ByVal i As Byte) As Byte
    Dim FF As Byte = 255
    Dim two As Byte = 2

    Return i + (FF - i) \ two
End Function

第一个实在是丑陋且难以阅读,因为 每一个 字面意思应该是 CByted.第二个以整数进行计算,然后将结果转换为字节,这可以,但不如纯字节操作那么优雅。第三种解决方法不需要 CBytes,但它的缺点也很明显。

我是否错过了一些(优雅的)第四个选项,它允许我进行仅字节数学运算,而不会用 CBool​​s 弄乱我的公式?

有帮助吗?

解决方案

Visual Basic 语言规范第 2.4.2 章中特别提到:

注解 >没有字节的类型字符,因为最自然的字符是b,这是十六进制文字中的合法特征。

嗯,我想确实如此。毫无疑问,“Octet”也被否决了。使用 Return CByte(...),它比 ToByte() 便宜。

其他提示

使用常量怎么样:

Function ReduceDistanceTo255(ByVal i As Byte) As Byte
  Const bFF As Byte = 255    
  Const b02 As Byte = 2
  Return i + (bFF - i) \ b02
End Function

没有转换,没有转换,没有额外的变量

简单的方法怎么样:

Imports System.Convert

Function ReduceDistanceTo255(ByVal i As Byte) As Byte
    Return ToByte(i + (255 - i) \ 2)
End Function

编辑: 我更喜欢这种解决方法,因为它会减少转换,而且我很清楚发生了什么。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top