代码之家  ›  专栏  ›  技术社区  ›  Heinzi

使用字节文本

  •  1
  • Heinzi  · 技术社区  · 16 年前

    我正在使用以下函数来增加颜色值(在我的代码中它是一个lambda,但这不会造成不同的效果):

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

    它不会编译,因为编译器解释 255 和 2 作为整数而不是字节,使类型的结果 Integer . 不幸的是, there is no Byte type character 所以我不能只写 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
    

    第一个很难看,很难读懂,因为 每一个 文字必须是 CByte d.第二个执行整数计算,然后将结果转换为字节,这是可以的,但没有纯字节操作那么优雅。第三个解决方案不需要 立方字节 但是它的缺点是显而易见的。

    我是否错过了一些(优雅的)第四个选项,它允许我做纯字节的数学而不把公式与cbool混淆?

    3 回复  |  直到 15 年前
        1
  •  4
  •   Hans Passant    16 年前

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

    注释 >没有一种类型 因为最 自然特性为b,即 十六进制的合法字符 字面意义的。

    嗯,我想是真的。”毫无疑问,“八重奏”也被否决了。使用返回cByte(…),它比toByte()便宜。

        2
  •  1
  •   Norm    15 年前

    如何使用常量:

    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
    

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

        3
  •  0
  •   Bobby    16 年前

    简单的方法如何:

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

    编辑: 我更喜欢这种变通方法,因为它可以减少施法次数,而且我很清楚发生了什么。