如何在VB.NET中声明固定长度的字符串?

14

我该如何声明一个像这样的字符串:

Dim strBuff As String * 256

在VB.NET中如何实现?

10个回答

7
使用VBFixedString属性。请参见此处的MSDN信息
<VBFixedString(256)>Dim strBuff As String

2
注释本身明显不足。在VB6中将上面示例中的strBuff设置为空字符串("")仍会产生一个带有256个空格的字符串。但这个.NET等效物则不会。该注释似乎主要用于提供信息,并且在大多数情况下并未强制执行字符串长度(我认为FilePut使用此信息)。 - ChristopheD
请参见此处的其他讨论:http://stackoverflow.com/questions/16996971/how-to-declare-a-fixed-length-string-in-vb-net-without-increasing-the-length-dur - StayOnTarget

7

这取决于您打算如何使用字符串。如果您要用它进行文件输入和输出,可能需要使用字节数组以避免编码问题。在VB.NET中,一个256个字符的字符串可能超过256个字节。

Dim strBuff(256) as byte

您可以使用编码将字节转换为字符串。
Dim s As String
Dim b(256) As Byte
Dim enc As New System.Text.UTF8Encoding
...
s = enc.GetString(b)

如果您需要使用字符串来接收数据,可以将256个单字节字符分配给它,但在vb.net中,参数传递可能与vb6不同。

s = New String(" ", 256)

此外,您还可以使用vbFixedString。我不确定它的确切作用是什么,因为当您将一个长度不同的字符串分配给以这种方式声明的变量时,它会变成新的长度。
<VBFixedString(6)> Public s As String
s = "1234567890" ' len(s) is now 10

VBFixedString只是指示VB6兼容的文件读/写操作要读取多少数据。据我所知,它不会以任何方式影响字符串对象本身。 - StayOnTarget

3
要编写这段VB 6代码:
Dim strBuff As String * 256

在VB.Net中,您可以使用类似以下的代码:
Dim strBuff(256) As Char

3
使用StringBuilder
'Declaration   
Dim S As New System.Text.StringBuilder(256, 256)
'Adding text
S.append("abc")
'Reading text
S.tostring

1
你可以使用 Microsoft.VisualBasic.Compatibility:
Imports Microsoft.VisualBasic.Compatibility

Dim strBuff As New VB6.FixedLengthString(256)

但是它被标记为已过时并且不支持64位进程, 因此请编写自己的代码以复制该功能,即在设置长值时截断并在短值右侧填充空格。 它还将"未初始化"的值(如上所述)设置为null。
来自LinqPad的示例代码(我无法让Imports Microsoft.VisualBasic.Compatibility工作,我认为这是因为它被标记为已过时,但我没有证据):
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()

该输出如下:

"\ 0 \ 0 \ 0 \ 0 \ 0"
  "测试"
  "Testi"
  "测试"
  "Testi"


1
这个对象可以定义为一个结构体,有一个构造函数和两个属性。
Public Structure FixedLengthString
     Dim mValue As String
     Dim mSize As Short

     Public Sub New(Size As Integer)
         mSize = Size
         mValue = New String(" ", mSize)
     End Sub

     Public Property Value As String
         Get
             Value = mValue
         End Get

         Set(value As String)
             If value.Length < mSize Then
                 mValue = value & New String(" ", mSize - value.Length)
             Else
                 mValue = value.Substring(0, mSize)
             End If
         End Set
     End Property
 End Structure

https://jdiazo.wordpress.com/2012/01/12/getting-rid-of-vb6-compatibility-references/


1

试试这个:

    Dim strbuf As New String("A", 80)

创建一个由“AAA…”填充的80个字符的字符串。
在这里,我从二进制文件中读取了一个80个字符的字符串。
    FileGet(1,strbuf)

读取80个字符到strbuf中...

-1
Dim a as string

a = ...

If a.length > theLength then

     a = Mid(a, 1, theLength)

End If

2
这不是一个固定长度的字符串。在代码的其余部分中,什么阻止了字符串的增长? - Lee Taylor

-1

你试过了吗?

Dim strBuff as String

还可以查看使用VB.NET在.NET中处理字符串

本教程解释了如何使用VB.NET在.NET中表示字符串,以及如何借助.NET类库类处理它们。


1
但是那里没有答案。 - Rachel
1
当然,但这不是我需要的。我需要他像在VB.6中声明它一样声明它。 - Rachel

-1

这个还没有完全测试,但是这里有一个类可以解决这个问题:

''' <summary>
''' Represents a <see cref="String" /> with a minimum
''' and maximum length.
''' </summary>
Public Class BoundedString

    Private mstrValue As String

    ''' <summary>
    ''' The contents of this <see cref="BoundedString" />
    ''' </summary>
    Public Property Value() As String
        Get
            Return mstrValue
        End Get

        Set(value As String)
            If value.Length < MinLength Then
                Throw New ArgumentException(String.Format("Provided string {0} of length {1} contains less " &
                                                          "characters than the minimum allowed length {2}.",
                                                          value, value.Length, MinLength))
            End If

            If value.Length > MaxLength Then
                Throw New ArgumentException(String.Format("Provided string {0} of length {1} contains more " &
                                                          "characters than the maximum allowed length {2}.",
                                                          value, value.Length, MaxLength))
            End If

            If Not AllowNull AndAlso value Is Nothing Then
                Throw New ArgumentNullException(String.Format("Provided string {0} is null, and null values " &
                                                              "are not allowed.", value))
            End If

            mstrValue = value
        End Set
    End Property

    Private mintMinLength As Integer
    ''' <summary>
    ''' The minimum number of characters in this <see cref="BoundedString" />.
    ''' </summary>
    Public Property MinLength() As Integer
        Get
            Return mintMinLength
        End Get

        Private Set(value As Integer)
            mintMinLength = value
        End Set

    End Property

    Private mintMaxLength As Integer
    ''' <summary>
    ''' The maximum number of characters in this <see cref="BoundedString" />.
    ''' </summary>
    Public Property MaxLength As Integer
        Get
            Return mintMaxLength
        End Get

        Private Set(value As Integer)
            mintMaxLength = value
        End Set
    End Property

    Private mblnAllowNull As Boolean
    ''' <summary>
    ''' Whether or not this <see cref="BoundedString" /> can represent a null value.
    ''' </summary>
    Public Property AllowNull As Boolean
        Get
            Return mblnAllowNull
        End Get

        Private Set(value As Boolean)
            mblnAllowNull = value
        End Set
    End Property

    Public Sub New(ByVal strValue As String,
                   ByVal intMaxLength As Integer)
        MinLength = 0
        MaxLength = intMaxLength
        AllowNull = False

        Value = strValue
    End Sub

    Public Sub New(ByVal strValue As String,
                   ByVal intMinLength As Integer,
                   ByVal intMaxLength As Integer)
        MinLength = intMinLength
        MaxLength = intMaxLength
        AllowNull = False

        Value = strValue
    End Sub

    Public Sub New(ByVal strValue As String,
                   ByVal intMinLength As Integer,
                   ByVal intMaxLength As Integer,
                   ByVal blnAllowNull As Boolean)
        MinLength = intMinLength
        MaxLength = intMaxLength
        AllowNull = blnAllowNull

        Value = strValue
    End Sub
End Class

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接