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

LenB对非字符串参数实际做了什么

  •  1
  • Tanj  · 技术社区  · 17 年前

    我有一段代码正在从vb6转换到vb.net。我需要知道LenB在这段代码中做了什么。

    Dim singleValue As Single 'var for conversion use(4byte -> 1single)'
    Dim bytes() As Byte
    Dim valueB() As Byte 'this gets set elsewhere and is redim-d to its size'
    
    For n = 0 To CDbl(ItemNumberCombo.Text) - 1
        'bytes() -> single'
        'UPGRADE_ISSUE: LenB function is not supported.'
        ReDim bytes(LenB(singleValue) - 1)
        bytes(3) = valueB(n * 4)
        bytes(2) = valueB(n * 4 + 1)
        bytes(1) = valueB(n * 4 + 2)
        bytes(0) = valueB(n * 4 + 3)
        'UPGRADE_ISSUE: LenB function is not supported.'
        'UPGRADE_ISSUE: VarPtr function is not supported. '
        Call memcpy(VarPtr(singleValue), VarPtr(bytes(0)), LenB(singleValue))
        'display the result'
        DText(n).Text = VB6.Format(singleValue, "0.000000E+00") 'CStr(singleValue)'
        If DataSaveCheckBox.CheckState = 1 And FileNameText.Text <> "" Then
            csvOutput = csvOutput & DText(n).Text & ","
        End If
    Next n
    

    我认为字节总是被重新调整为相同的大小,对吗?从外观上看,有四个元素。

    2 回复  |  直到 17 年前
        1
  •  4
  •   Joel Coehoorn    13 年前

    LenB()返回变量的长度(以字节为单位)。最常见的例子是字符串,无论字符编码如何,它都会返回字符串的大小(以字节为单位),而不是字符数。对于其他类型,它返回对象的大小——单个对象的大小为4。他们这样做的原因是,如果visual basic的未来版本改变了单个代码的大小,他们希望代码能够存活下来(更不用说在分配字节数组时对数字4进行硬编码了)。

    将LenB()升级到时。Net,用于字符串 System.Text.Encoding.Unicode.GetBytes() 获取一个已经填充了字符串文本字节的数组。记住这一点。Net内部总是使用Unicode作为字符串。如果您真的需要不同的编码,encoding命名空间中有许多替代方案。对于其他类型,请使用 BitConverter 类。无论哪种方式,都不要逐行进行,因为新方法会带走很多繁忙的工作。

    在这里,我会帮你完成一些转换:

    (较早)

    Dim csvOutput As New StringBuilder()
    

    (稍后)

    Dim valueB() As Byte 'this gets set elsewhere and is redim-d to its size'
    Dim singleValue As Single 'var for conversion
    
    ' Included because the original developer was concerned the size of a single could change
    Dim singleSize As Integer = BitConverter.GetBytes(singleValue).Length 
    
    Dim NumberItems As Double
    If Double.TryParse(ItemNumberCombo.Text, NumberItems) Then
        For n As Integer = 0 To NumberItems - 1
            singleValue = BitConverter.ToSingle(valueB, n * singleSize)
    
            'display the result
            DText(n).Text = singleValue.ToString("E6") 'CStr(singleValue)
            If DataSaveCheckBox.CheckState = 1 AndAlso Not String.IsNullOrEmpty(FileNameText.Text) Then
                csvOutput.Append(DText(n).Text & ",")
            End If
        Next n
    Else
        ' Handle Invalid ComboBox value here- may not be an issue for you
    End If
    

    请注意,此代码还演示了 StringBuilder 作为 许多 AndAlso 操作员 .TryParse() String.IsNullOrEmpty() ,以及标准格式字符串,所有这些都旨在替换vb6中的构造或技术。

        2
  •  3
  •   Will Rickards    17 年前

    试图解释糟糕的代码。..这只是徒劳的努力。 通过加载字节数组来填充Single的有趣方法。

    LenB函数为您提供变量的长度(以字节为单位)。 是的,当传递Single变量类型时,它总是返回4。

    我对redim的猜测是,数组会被初始化而不是保留。 但由于它随后分配了所有4个字节,因此在技术上并不需要,可能只是防御性编程。防御性编程也可能解释LenB。以防Single将来更改大小。