Ler en inglés

Compartir por


DecoderExceptionFallback Clase

Definición

Proporciona un mecanismo de control de errores, denominado reserva, relativo a una secuencia codificada de bytes de entrada que no se puede convertir en un carácter de entrada. La reserva produce una excepción en lugar de descodificar la secuencia de bytes de entrada. Esta clase no puede heredarse.

C#
public sealed class DecoderExceptionFallback : System.Text.DecoderFallback
C#
[System.Serializable]
public sealed class DecoderExceptionFallback : System.Text.DecoderFallback
Herencia
DecoderExceptionFallback
Atributos

Ejemplos

En el ejemplo de código siguiente se muestran las DecoderExceptionFallback clases y DecoderFallbackException .

C#
// This example demonstrates the DecoderExceptionFallback class.

using System;
using System.Text;

class Sample
{
    public static void Main()
    {

// Create an encoding, which is equivalent to calling the
// ASCIIEncoding class constructor.
// The DecoderExceptionFallback parameter specifies that an exception
// is thrown if a character cannot be encoded.
// An encoder exception fallback is also specified, but in this code
// example the encoding operation cannot fail.

    Encoding ae = Encoding.GetEncoding(
                  "us-ascii",
                  new EncoderExceptionFallback(),
                  new DecoderExceptionFallback());
    string inputString = "XYZ";
    string decodedString;
    string twoNewLines = "\n\n";
    byte[] encodedBytes = new byte[ae.GetByteCount(inputString)];
    int numberOfEncodedBytes = 0;

// --------------------------------------------------------------------------
    Console.Clear();

// Display the name of the encoding.
    Console.WriteLine("The name of the encoding is \"{0}\".\n", ae.WebName);

// Display the input string in text.
    Console.WriteLine("Input string ({0} characters): \"{1}\"",
                       inputString.Length, inputString);

// Display the input string in hexadecimal.
    Console.Write("Input string in hexadecimal: ");
    foreach (char c in inputString.ToCharArray())
        {
        Console.Write("0x{0:X2} ", (int)c);
        }
    Console.Write(twoNewLines);

// --------------------------------------------------------------------------
// Encode the input string.

    Console.WriteLine("Encode the input string...");
    numberOfEncodedBytes = ae.GetBytes(inputString, 0, inputString.Length,
                                       encodedBytes, 0);
// Display the encoded bytes.
    Console.WriteLine("Encoded bytes in hexadecimal ({0} bytes):\n",
                       numberOfEncodedBytes);
    foreach (byte b in encodedBytes)
        {
        Console.Write("0x{0:X2} ", (int)b);
        }
    Console.Write(twoNewLines);

// --------------------------------------------------------------------------

// Replace the encoded byte sequences for the characters 'X' and 'Z' with the
// value 0xFF, which is outside the valid range of 0x00 to 0x7F for
// ASCIIEncoding. The resulting byte sequence is actually the beginning of
// this code example because it is the input to the decoder operation, and
// is equivalent to a corrupted or improperly encoded byte sequence.

    encodedBytes[0] = 0xFF;
    encodedBytes[2] = 0xFF;

    Console.WriteLine("Display the corrupted byte sequence...");
    Console.WriteLine("Encoded bytes in hexadecimal ({0} bytes):\n",
                       numberOfEncodedBytes);
    foreach (byte b in encodedBytes)
        {
        Console.Write("0x{0:X2} ", (int)b);
        }
    Console.Write(twoNewLines);

// --------------------------------------------------------------------------
// Attempt to decode the encoded bytes. However, an exception is thrown
// before the byte sequence can be decoded.

    Console.WriteLine("Compare the decoded bytes to the input string...");

    try {
        decodedString = ae.GetString(encodedBytes);
        }
    catch (DecoderFallbackException dfe)
        {
        Console.WriteLine(dfe);
        Console.WriteLine("\n*** THE CODE EXAMPLE TERMINATES HERE AS INTENDED. ***");
        return;
        }

// This statement is never executed.
    Console.WriteLine("This statement is never executed.");
    }
}
/*
This code example produces the following results:

The name of the encoding is "us-ascii".

Input string (3 characters): "XYZ"
Input string in hexadecimal: 0x58 0x59 0x5A

Encode the input string...
Encoded bytes in hexadecimal (3 bytes):

0x58 0x59 0x5A

Display the corrupted byte sequence...
Encoded bytes in hexadecimal (3 bytes):

0xFF 0x59 0xFF

Compare the decoded bytes to the input string...
System.Text.DecoderFallbackException: Unable to translate bytes [FF] at index 0 from speci
fied code page to Unicode.
   at System.Text.DecoderExceptionFallbackBuffer.Throw(Byte[] bytesUnknown, Int32 index)
   at System.Text.DecoderExceptionFallbackBuffer.Fallback(Byte[] bytesUnknown, Int32 index
)
   at System.Text.DecoderFallbackBuffer.InternalFallback(Byte[] bytes, Byte* pBytes)
   at System.Text.ASCIIEncoding.GetCharCount(Byte* bytes, Int32 count, DecoderNLS decoder)

   at System.String.CreateStringFromEncoding(Byte* bytes, Int32 byteLength, Encoding encod
ing)
   at System.Text.ASCIIEncoding.GetString(Byte[] bytes, Int32 byteIndex, Int32 byteCount)
   at System.Text.Encoding.GetString(Byte[] bytes)
   at Sample.Main()

*** THE CODE EXAMPLE TERMINATES HERE AS INTENDED. ***

*/

Comentarios

Una codificación asigna un carácter Unicode a una secuencia codificada de bytes, que posteriormente se puede transferir a un medio físico, como un disco o a través de un vínculo de comunicaciones. Los caracteres se pueden asignar de varias maneras y una codificación determinada se representa mediante un tipo derivado de la Encoding clase . En concreto, el método del GetBytes tipo de codificación codifica un carácter en una secuencia de bytes y el GetChars método descodifica una secuencia de bytes en un carácter.

Se puede producir un error en una operación de descodificación si la secuencia de bytes de entrada no se puede asignar mediante la codificación. Por ejemplo, un ASCIIEncoding objeto no puede descodificar una secuencia de bytes que produce un carácter que tiene un valor de punto de código que está fuera del intervalo U+0000 a U+007F.

En los casos en los que no se puede realizar una conversión de codificación o descodificación, .NET Framework proporciona un mecanismo de control de errores denominado reserva. La aplicación puede usar la reserva de descodificador de .NET Framework predefinida, o bien puede crear una reserva de descodificador personalizada derivada de las DecoderFallback clases y DecoderFallbackBuffer .

.NET Framework proporciona dos clases predefinidas que implementan estrategias de reserva diferentes para controlar errores de conversión de descodificación. La DecoderReplacementFallback clase sustituye una cadena proporcionada en lugar de cualquier secuencia de bytes de entrada que no se pueda convertir. Una vez emitida la cadena de sustitución, la operación de descodificación continúa convirtiendo el resto de la entrada. Por el contrario, la DecoderExceptionFallback clase produce un DecoderFallbackException cuando se encuentra una secuencia de bytes no válida.

Constructores

DecoderExceptionFallback()

Inicializa una nueva instancia de la clase DecoderExceptionFallback.

Propiedades

MaxCharCount

Obtiene el número máximo de caracteres que esta instancia puede devolver.

Métodos

CreateFallbackBuffer()

Devuelve un búfer de reserva del descodificador que produce una excepción si no puede convertir una secuencia de bytes en un carácter.

Equals(Object)

Indica si el objeto DecoderExceptionFallback actual y un objeto especificado son iguales.

GetHashCode()

Recupera el código hash de esta instancia.

GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Se aplica a

Produto Versións
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Consulte también