2010-02-21 91 views

Respuesta

-1

Ha intentado

Dim strBuff as String 

Véase también Working with Strings in .NET using VB.NET

Este tutorial explica cómo representan cadenas en .NET utilizando VB.NET y cómo trabajar con ellos con la ayuda de Clases de biblioteca de clases .NET.

+1

Pero hay una respuesta is'nt no – Rachel

+1

, por supuesto, pero esto no es lo que necesito. Necesito que lo declare como ha sido declarado en vb.6 – Rachel

7

Utilice el atributo VBFixedString. Ver la información de MSDN here

<VBFixedString(256)>Dim strBuff As String 
+2

La anotación en sí es muy insuficiente. Establecer 'strBuff' del ejemplo anterior en una cadena vacía (" '') en VB6 todavía produciría una cadena con 256 espacios. Este equivalente de .NET no. La anotación parece ser principalmente informativa y no * aplica * mucho sobre las longitudes de cadena en la mayoría de los casos (creo que FilePut usa la información). – ChristopheD

+0

Consulte la discusión adicional aquí: http://stackoverflow.com/questions/16996971/how-to-declare-a-fixed-length-string-in-vb-net-without-increasing-the-length-dur – DaveInCaz

3

Para escribir el código VB 6:

Dim strBuff As String * 256 

en VB.Net se puede usar algo como:

Dim strBuff(256) As Char 
5

Depende de lo que se propone usa la cuerda para. Si lo está utilizando para la entrada y salida de archivos, es posible que desee utilizar una matriz de bytes para evitar problemas de codificación. En vb.net, una cadena de 256 caracteres puede tener más de 256 bytes.

Dim strBuff(256) as byte 

Puede utilizar la codificación para la transferencia de bytes en una cadena

Dim s As String 
Dim b(256) As Byte 
Dim enc As New System.Text.UTF8Encoding 
... 
s = enc.GetString(b) 

Puede asignar 256 caracteres de un solo byte en una cadena si es necesario usarlo para recibir datos, pero el paso de parámetros puede ser diferente en vb.net que vb6.

s = New String(" ", 256) 

Además, puede usar vbFixedString. Sin embargo, no estoy seguro de qué es exactamente lo que hace, porque cuando asigna una cadena de longitud diferente a una variable declarada de esta manera, se convierte en la nueva longitud.

<VBFixedString(6)> Public s As String 
s = "1234567890" ' len(s) is now 10 
-1
Dim a as string 

a = ... 

If a.length > theLength then 

    a = Mid(a, 1, theLength) 

End If 
+2

This isn No es una cadena de longitud fija. ¿Qué impide que la cadena crezca en el resto del código? –

2

Uso StringBuilder

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

Prueba esto:

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

crea una cadena de 80 caracteres lleno de "AAA ...." 's

Aquí estoy ead una cadena de 80 caracteres de un archivo binario:

FileGet(1,strbuf) 

lee 80 caracteres en strbuf ...

1

Puede utilizar Microsoft.VisualBasic.Compatibility:

Imports Microsoft.VisualBasic.Compatibility 

Dim strBuff As New VB6.FixedLengthString(256) 

pero es marcado como obsolete and specifically not supported for 64-bit processes, por lo que escribir su propia que replica la funcionalidad, que es truncar el establecimiento de valores de largo y relleno derecho con espacios para los valores cortos. También establece un valor "no inicializado", como el anterior, en nulos.

código de ejemplo de LINQPad (que no puedo conseguir para permitir Imports Microsoft.VisualBasic.Compatibility creo porque está marcado obsoleto, pero no tengo ninguna prueba de ello):

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() 

que tiene esta salida:

"\ 0 \ 0 \ 0 \ 0 \ 0"
"Prueba"
"Testi"
"Prueba"
"Testi"

-1

Esto no ha sido completamente probado, pero aquí es una clase para resolver este problema:

''' <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 
1

Este objeto se puede definir como una estructura con un constructor y dos propiedades.

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/

Cuestiones relacionadas