Pregunta

Ayer me hizo esta pregunta . Rubens Farías contestó señalando a este pieza de código , escribió. La siguiente parte de la misma no puede ser compilado por MS Visual Studio 2010 Professional Beta 2.

byte[] buffer = 
Encoding.UTF8.GetBytes(
    String.Join("&", 
        Array.ConvertAll<KeyValuePair<string, string>, string>(
            inputs.ToArray(),
            delegate(KeyValuePair item)
            {
                return item.Key + "=" + HttpUtility.UrlEncode(item.Value);
            })));

estos errores en Visual Studio. Desafortunadamente Rubens no responde más.

Así que tengo las siguientes preguntas / peticiones:

  1. No entiendo esta pieza de código, por favor explique lo que está ocurriendo exactamente.
  2. Por favor explicar cómo esta parte tiene que reescribirse te a fin de que a "trabajar" en VS.
  3. Por favor, explique cómo debería convertirlo en VB.NET. He probado el uso de convertidores en línea en vano.
¿Fue útil?

Solución

  • KeyValuePair requiere dos argumentos de tipo. En su declaración de delegado que dice simplemente KeyValuePair item, sin argumentos de tipo. Cambie esto a delegate(KeyValuePair<string,string> item)
  • HttpUtility se declara en el espacio de nombres System.Web; añadir using System.Web; a las instrucciones using al principio del archivo.

En lo personal me resulta más fácil y más limpio para el uso de estilo lambda para este tipo de código:

byte[] buffer =
     Encoding.UTF8.GetBytes(
         String.Join("&",
             Array.ConvertAll<KeyValuePair<string, string>, string>(
                 inputs.ToArray(), (item) => item.Key + "=" + HttpUtility.UrlEncode(item.Value))));

Una vez que haya recibido el código C # para el trabajo, la DeveloperFusion C # para VB.NET convertidor se encarga del trabajo:

' Converted from delegate style C# implementation '
Dim buffer As Byte() = Encoding.UTF8.GetBytes( _
    [String].Join("&", _
    Array.ConvertAll(Of KeyValuePair(Of String, String), String)(inputs.ToArray(), _
        Function(item As KeyValuePair(Of String, String)) (item.Key & "=") + HttpUtility.UrlEncode(item.Value))))

' Converted from Lambda style C# implementation '
Dim buffer As Byte() = Encoding.UTF8.GetBytes( _
    [String].Join("&", _
    Array.ConvertAll(Of KeyValuePair(Of String, String), String)(inputs.ToArray(), _
        Function(item) (item.Key & "=") + HttpUtility.UrlEncode(item.Value))))

Otros consejos

byte[] buffer = 
Encoding.UTF8.GetBytes(
    String.Join("&", 
        Array.ConvertAll<KeyValuePair<string, string>, string>(
            inputs.ToArray(),
            delegate(KeyValuePair<string, string> item)
            {
                return item.Key + "=" + System.Web.HttpUtility.UrlEncode(item.Value);
            })));

Trate de eso.

  1. El código parece estar construyendo una lista de peticiones GET de artículos, por ejemplo, key1=value1&key2=value2. Esto se realiza mediante la conversión primero la matriz inputs en elementos individuales de key=value entonces String.Joining ellos junto con una y comercial. A continuación, devuelve la UTF8 bytes en una matriz.

  2. Estos trabajos (ver código).

  3. No soy un programador VB.NET, lo siento, pero voy a tener un ir en un segundo.

es la conversión de la lista de entradas que contiene pares clave / valor en una cadena que se parece mucho a una cadena de consulta (por ejemplo. Item1 = valor1 y item2 = valor2), entonces la conversión que en la matriz de bytes buffer usando codificación UTF8.

Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim inputs As New List(Of KeyValuePair(Of String, String))
        inputs.Add(New KeyValuePair(Of String, String)("a", "adata"))

        Dim buffer As Byte() = _
            Encoding.UTF8.GetBytes( _
                String.Join("&", _
                Array.ConvertAll(Of KeyValuePair(Of String, String), String)( _
                    inputs.ToArray(), _
                    Function(item As KeyValuePair(Of String, String)) _
                    item.Key & "=" & HttpUtility.UrlEncode(item.Value) _
                )))
    End Sub
End Class
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top