How to declare a fixed-length string in VB.NET?

前端 未结 10 2978
醉酒成梦
醉酒成梦 2020-12-10 04:27

How do i Declare a string like this:

Dim strBuff As String * 256

in VB.NET?

10条回答
  •  温柔的废话
    2020-12-10 05:04

    You can use Microsoft.VisualBasic.Compatibility:

    Imports Microsoft.VisualBasic.Compatibility
    
    Dim strBuff As New VB6.FixedLengthString(256)
    

    But it's marked as obsolete and specifically not supported for 64-bit processes, so write your own that replicates the functionality, which is to truncate on setting long values and padding right with spaces for short values. It also sets an "uninitialised" value, like above, to nulls.

    Sample code from LinqPad (which I can't get to allow Imports Microsoft.VisualBasic.Compatibility I think because it is marked obsolete, but I have no proof of that):

    Imports Microsoft.VisualBasic.Compatibility
    
    Dim U As New VB6.FixedLengthString(5)
    Dim S As New VB6.FixedLengthString(5, "Test")
    Dim L As New VB6.FixedLengthString(5, "Testing")
    Dim p0 As Func(Of String, String) = Function(st) """" & st.Replace(ChrW(0), "\0") & """"
    p0(U.Value).Dump()
    p0(S.Value).Dump()
    p0(L.Value).Dump()
    U.Value = "Test"
    p0(U.Value).Dump()
    U.Value = "Testing"
    p0(U.Value).Dump()
    

    which has this output:

    "\0\0\0\0\0"
    "Test "
    "Testi"
    "Test "
    "Testi"

提交回复
热议问题