NotSupportedException Clase
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Excepción que se produce cuando un método invocado no es compatible o cuando se intenta leer, buscar o escribir en una secuencia que no es compatible con las funciones invocadas.
public ref class NotSupportedException : Exception
public ref class NotSupportedException : SystemException
public class NotSupportedException : Exception
public class NotSupportedException : SystemException
[System.Serializable]
public class NotSupportedException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class NotSupportedException : SystemException
type NotSupportedException = class
inherit Exception
type NotSupportedException = class
inherit SystemException
[<System.Serializable>]
type NotSupportedException = class
inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type NotSupportedException = class
inherit SystemException
Public Class NotSupportedException
Inherits Exception
Public Class NotSupportedException
Inherits SystemException
- Herencia
- Herencia
- Derivado
- Atributos
Comentarios
NotSupportedException indica que no existe ninguna implementación para un método o propiedad invocado.
NotSupportedException usa el COR_E_NOTSUPPORTED HRESULT, que tiene el valor 0x80131515.
Para obtener una lista de valores de propiedad iniciales de una instancia de NotSupportedException, consulte el NotSupportedException constructores.
Iniciar una excepción NotSupportedException
Puede considerar la posibilidad de producir una NotSupportedException excepción en los casos siguientes:
Está implementando una interfaz de uso general y el número de métodos no tienen ninguna implementación significativa. Por ejemplo, si va a crear un tipo de fecha y hora que implemente la IConvertible interfaz , produciría una NotSupportedException excepción para la mayoría de las conversiones.
Ha heredado de una clase abstracta que requiere que invalide varios métodos. Sin embargo, solo está preparado para proporcionar una implementación para un subconjunto de estos. Para los métodos que decida no implementar, puede elegir iniciar una NotSupportedExceptionexcepción .
Está definiendo un tipo de uso general con un estado que habilita las operaciones condicionalmente. Por ejemplo, el tipo puede ser de solo lectura o de lectura y escritura. En tal caso:
Si el objeto es de solo lectura, al intentar asignar valores a las propiedades de una instancia o llamar a métodos que modifican el estado de instancia, se debería producir una NotSupportedException excepción.
Debe implementar una propiedad que devuelva un Boolean valor que indique si hay una funcionalidad determinada disponible. Por ejemplo, para un tipo que puede ser de solo lectura o de lectura y escritura, podría implementar una
IsReadOnly
propiedad que indique si el conjunto de métodos de lectura y escritura está disponible o no disponible.
Control de una excepción NotSupportedException
La NotSupportedException excepción indica que un método no tiene ninguna implementación y que no debe llamarlo. No debe controlar la excepción. En su lugar, lo que debe hacer depende de la causa de la excepción: si una implementación está completamente ausente o la invocación de miembro es incoherente con el propósito de un objeto (por ejemplo, una llamada al FileStream.Write método en un objeto de solo FileStream lectura .
No se ha proporcionado una implementación porque la operación no se puede realizar de forma significativa.
Se trata de una excepción común cuando se llama a métodos en un objeto que proporciona implementaciones para los métodos de una clase base abstracta, o que implementa una interfaz de uso general y el método no tiene ninguna implementación significativa.
Por ejemplo, la Convert clase implementa la IConvertible interfaz , lo que significa que debe incluir un método para convertir todos los tipos primitivos en todos los demás tipos primitivos. Sin embargo, muchas de esas conversiones no son posibles. Como resultado, una llamada al Convert.ToBoolean(DateTime) método, por ejemplo, produce una NotSupportedException excepción porque no hay ninguna conversión posible entre y DateTime un Boolean valor.
Para eliminar la excepción, debe eliminar la llamada al método .
La llamada al método no se admite según el estado del objeto .
Está intentando invocar a un miembro cuya funcionalidad no está disponible debido al estado del objeto. Puede eliminar la excepción de una de estas tres maneras:
Conoce el estado del objeto de antemano, pero ha invocado un método o propiedad no admitidos. En este caso, la invocación de miembro es un error y puede eliminarla.
Conoce el estado del objeto de antemano (normalmente porque el código ha creado una instancia de él), pero el objeto está mal configurado. En el ejemplo siguiente se muestra este problema. Crea un objeto de solo FileStream lectura y, a continuación, intenta escribir en él.
using System; using System.IO; using System.Text; using System.Threading.Tasks; public class Example { public static async Task Main() { Encoding enc = Encoding.Unicode; String value = "This is a string to persist."; Byte[] bytes = enc.GetBytes(value); FileStream fs = new FileStream(@".\TestFile.dat", FileMode.Open, FileAccess.Read); Task t = fs.WriteAsync(enc.GetPreamble(), 0, enc.GetPreamble().Length); Task t2 = t.ContinueWith( (a) => fs.WriteAsync(bytes, 0, bytes.Length) ); await t2; fs.Close(); } } // The example displays the following output: // Unhandled Exception: System.NotSupportedException: Stream does not support writing. // at System.IO.Stream.BeginWriteInternal(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state // , Boolean serializeAsynchronously) // at System.IO.FileStream.BeginWrite(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback userCallback, Object sta // teObject) // at System.IO.Stream.<>c.<BeginEndWriteAsync>b__53_0(Stream stream, ReadWriteParameters args, AsyncCallback callback, // Object state) // at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim[TInstance,TArgs](TInstance thisRef, TArgs args, Func`5 beginMet // hod, Func`3 endMethod) // at System.IO.Stream.BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count) // at System.IO.FileStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) // at System.IO.Stream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count) // at Example.Main()
open System.IO open System.Text let main = task { let enc = Encoding.Unicode let value = "This is a string to persist." let bytes = enc.GetBytes value let fs = new FileStream(@".\TestFile.dat", FileMode.Open, FileAccess.Read) let t = fs.WriteAsync(enc.GetPreamble(), 0, enc.GetPreamble().Length) let t2 = t.ContinueWith(fun a -> fs.WriteAsync(bytes, 0, bytes.Length)) let! _ = t2 fs.Close() } main.Wait() // The example displays the following output: // Unhandled Exception: System.NotSupportedException: Stream does not support writing. // at System.IO.Stream.BeginWriteInternal(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state // , Boolean serializeAsynchronously) // at System.IO.FileStream.BeginWrite(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback userCallback, Object sta // teObject) // at System.IO.Stream.<>c.<BeginEndWriteAsync>b__53_0(Stream stream, ReadWriteParameters args, AsyncCallback callback, // Object state) // at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim[TInstance,TArgs](TInstance thisRef, TArgs args, Func`5 beginMet // hod, Func`3 endMethod) // at System.IO.Stream.BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count) // at System.IO.FileStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) // at System.IO.Stream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count) // at <StartupCode:fs>.main()
Imports System.IO Imports System.Text Imports System.Threading.Tasks Module Example Public Sub Main() Dim enc As Encoding = Encoding.Unicode Dim value As String = "This is a string to persist." Dim bytes() As Byte = enc.GetBytes(value) Dim fs As New FileStream(".\TestFile.dat", FileMode.Open, FileAccess.Read) Dim t As Task = fs.WriteAsync(enc.GetPreamble(), 0, enc.GetPreamble().Length) Dim t2 As Task = t.ContinueWith(Sub(a) fs.WriteAsync(bytes, 0, bytes.Length)) t2.Wait() fs.Close() End Sub End Module ' The example displays the following output: ' Unhandled Exception: System.NotSupportedException: Stream does not support writing. ' at System.IO.Stream.BeginWriteInternal(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state ' , Boolean serializeAsynchronously) ' at System.IO.FileStream.BeginWrite(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback userCallback, Object sta ' teObject) ' at System.IO.Stream.<>c.<BeginEndWriteAsync>b__53_0(Stream stream, ReadWriteParameters args, AsyncCallback callback, ' Object state) ' at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim[TInstance,TArgs](TInstance thisRef, TArgs args, Func`5 beginMet ' hod, Func`3 endMethod) ' at System.IO.Stream.BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count) ' at System.IO.FileStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) ' at System.IO.Stream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count) ' at Example.Main()
Puede eliminar la excepción asegurándose de que el objeto creado por instancias admita la funcionalidad que pretende. En el ejemplo siguiente se soluciona el problema del objeto de solo FileStream lectura proporcionando los argumentos correctos al FileStream.FileStream(String, FileMode, FileAccess) constructor.
No conoce el estado del objeto de antemano y el objeto no admite una operación determinada. En la mayoría de los casos, el objeto debe incluir una propiedad o un método que indique si admite un conjunto determinado de operaciones. Puede eliminar la excepción comprobando el valor del objeto e invocando el miembro solo si procede.
En el ejemplo siguiente se define un
DetectEncoding
método que produce una NotSupportedException excepción cuando intenta leer desde el principio de una secuencia que no admite el acceso de lectura.using System; using System.IO; using System.Threading.Tasks; public class Example { public static async Task Main() { String name = @".\TestFile.dat"; var fs = new FileStream(name, FileMode.Create, FileAccess.Write); Console.WriteLine("Filename: {0}, Encoding: {1}", name, await FileUtilities.GetEncodingType(fs)); } } public class FileUtilities { public enum EncodingType { None = 0, Unknown = -1, Utf8 = 1, Utf16 = 2, Utf32 = 3 } public async static Task<EncodingType> GetEncodingType(FileStream fs) { Byte[] bytes = new Byte[4]; int bytesRead = await fs.ReadAsync(bytes, 0, 4); if (bytesRead < 2) return EncodingType.None; if (bytesRead >= 3 & (bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)) return EncodingType.Utf8; if (bytesRead == 4) { var value = BitConverter.ToUInt32(bytes, 0); if (value == 0x0000FEFF | value == 0xFEFF0000) return EncodingType.Utf32; } var value16 = BitConverter.ToUInt16(bytes, 0); if (value16 == (ushort)0xFEFF | value16 == (ushort)0xFFFE) return EncodingType.Utf16; return EncodingType.Unknown; } } // The example displays the following output: // Unhandled Exception: System.NotSupportedException: Stream does not support reading. // at System.IO.FileStream.BeginRead(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback callback, Object state) // at System.IO.Stream.<>c.<BeginEndReadAsync>b__46_0(Stream stream, ReadWriteParameters args, AsyncCallback callback, Object state) // at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim[TInstance, TArgs](TInstance thisRef, TArgs args, Func`5 beginMethod, Func`3 endMethod) // at System.IO.Stream.BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count) // at System.IO.FileStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) // at System.IO.Stream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count) // at FileUtilities.GetEncodingType(FileStream fs) in C:\Work\docs\program.cs:line 26 // at Example.Main() in C:\Work\docs\program.cs:line 13 // at Example.<Main>()
open System open System.IO module FileUtilities = type EncodingType = | None = 0 | Unknown = -1 | Utf8 = 1 | Utf16 = 2 | Utf32 = 3 let getEncodingType (fs: FileStream) = task { let bytes = Array.zeroCreate<byte> 4 let! bytesRead = fs.ReadAsync(bytes, 0, 4) if bytesRead < 2 then return EncodingType.None elif bytesRead >= 3 && bytes[0] = 0xEFuy && bytes[1] = 0xBBuy && bytes[2] = 0xBFuy then return EncodingType.Utf8 else let value = BitConverter.ToUInt32(bytes, 0) if bytesRead = 4 && (value = 0x0000FEFFu || value = 0xFEFF0000u) then return EncodingType.Utf32 else let value16 = BitConverter.ToUInt16(bytes, 0) if value16 = 0xFEFFus || value16 = 0xFFFEus then return EncodingType.Utf16 else return EncodingType.Unknown } let main _ = task { let name = @".\TestFile.dat" let fs = new FileStream(name, FileMode.Create, FileAccess.Write) let! et = FileUtilities.getEncodingType fs printfn $"Filename: {name}, Encoding: {et}" } // The example displays the following output: // Unhandled Exception: System.NotSupportedException: Stream does not support reading. // at System.IO.FileStream.BeginRead(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback callback, Object state) // at System.IO.Stream.<>c.<BeginEndReadAsync>b__46_0(Stream stream, ReadWriteParameters args, AsyncCallback callback, Object state) // at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim[TInstance, TArgs](TInstance thisRef, TArgs args, Func`5 beginMethod, Func`3 endMethod) // at System.IO.Stream.BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count) // at System.IO.FileStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) // at System.IO.Stream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count) // at FileUtilities.GetEncodingType(FileStream fs) // at Example.Main() // at Example.<Main>()
Imports System.IO Imports System.Threading.Tasks Module Example Public Sub Main() Dim name As String = ".\TestFile.dat" Dim fs As New FileStream(name, FileMode.Create, FileAccess.Write) Console.WriteLine("Filename: {0}, Encoding: {1}", name, FileUtilities.GetEncodingType(fs)) End Sub End Module Public Class FileUtilities Public Enum EncodingType As Integer None = 0 Unknown = -1 Utf8 = 1 Utf16 = 2 Utf32 = 3 End Enum Public Shared Function GetEncodingType(fs As FileStream) As EncodingType Dim bytes(3) As Byte Dim t As Task(Of Integer) = fs.ReadAsync(bytes, 0, 4) t.Wait() Dim bytesRead As Integer = t.Result If bytesRead < 2 Then Return EncodingType.None If bytesRead >= 3 And (bytes(0) = &hEF AndAlso bytes(1) = &hBB AndAlso bytes(2) = &hBF) Then Return EncodingType.Utf8 End If If bytesRead = 4 Then Dim value As UInteger = BitConverter.ToUInt32(bytes, 0) If value = &h0000FEFF Or value = &hFEFF0000 Then Return EncodingType.Utf32 End If End If Dim value16 As UInt16 = BitConverter.ToUInt16(bytes, 0) If value16 = &hFEFF Or value16 = &hFFFE Then Return EncodingType.Utf16 End If Return EncodingType.Unknown End Function End Class ' The example displays the following output: ' Unhandled Exception: System.NotSupportedException: Stream does not support reading. ' at System.IO.Stream.BeginReadInternal(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state, ' Boolean serializeAsynchronously) ' at System.IO.FileStream.BeginRead(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback userCallback, Object stat ' eObject) ' at System.IO.Stream.<>c.<BeginEndReadAsync>b__43_0(Stream stream, ReadWriteParameters args, AsyncCallback callback, O ' bject state) ' at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim[TInstance,TArgs](TInstance thisRef, TArgs args, Func`5 beginMet ' hod, Func`3 endMethod) ' at System.IO.Stream.BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count) ' at System.IO.FileStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) ' at System.IO.Stream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count) ' at FileUtilities.GetEncodingType(FileStream fs) ' at Example.Main()
Puede eliminar la excepción examinando el valor de la FileStream.CanRead propiedad y saliendo del método si la secuencia es de solo lectura.
public static async Task<EncodingType> GetEncodingType(FileStream fs) { if (!fs.CanRead) return EncodingType.Unknown; Byte[] bytes = new Byte[4]; int bytesRead = await fs.ReadAsync(bytes, 0, 4); if (bytesRead < 2) return EncodingType.None; if (bytesRead >= 3 & (bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)) return EncodingType.Utf8; if (bytesRead == 4) { var value = BitConverter.ToUInt32(bytes, 0); if (value == 0x0000FEFF | value == 0xFEFF0000) return EncodingType.Utf32; } var value16 = BitConverter.ToUInt16(bytes, 0); if (value16 == (ushort)0xFEFF | value16 == (ushort)0xFFFE) return EncodingType.Utf16; return EncodingType.Unknown; } } // The example displays the following output: // Filename: .\TestFile.dat, Encoding: Unknown
let getEncodingType (fs: FileStream) = task { if not fs.CanRead then return EncodingType.Unknown else let bytes = Array.zeroCreate<byte> 4 let! bytesRead = fs.ReadAsync(bytes, 0, 4) if bytesRead < 2 then return EncodingType.None elif bytesRead >= 3 && bytes[0] = 0xEFuy && bytes[1] = 0xBBuy && bytes[2] = 0xBFuy then return EncodingType.Utf8 else let value = BitConverter.ToUInt32(bytes, 0) if bytesRead = 4 && (value = 0x0000FEFFu || value = 0xFEFF0000u) then return EncodingType.Utf32 else let value16 = BitConverter.ToUInt16(bytes, 0) if value16 = 0xFEFFus || value16 = 0xFFFEus then return EncodingType.Utf16 else return EncodingType.Unknown } // The example displays the following output: // Filename: .\TestFile.dat, Encoding: Unknown
Public Class FileUtilities Public Enum EncodingType As Integer None = 0 Unknown = -1 Utf8 = 1 Utf16 = 2 Utf32 = 3 End Enum Public Shared Function GetEncodingType(fs As FileStream) As EncodingType If Not fs.CanRead Then Return EncodingType.Unknown Dim bytes(3) As Byte Dim t As Task(Of Integer) = fs.ReadAsync(bytes, 0, 4) t.Wait() Dim bytesRead As Integer = t.Result If bytesRead < 2 Then Return EncodingType.None If bytesRead >= 3 And (bytes(0) = &hEF AndAlso bytes(1) = &hBB AndAlso bytes(2) = &hBF) Then Return EncodingType.Utf8 End If If bytesRead = 4 Then Dim value As UInteger = BitConverter.ToUInt32(bytes, 0) If value = &h0000FEFF Or value = &hFEFF0000 Then Return EncodingType.Utf32 End If End If Dim value16 As UInt16 = BitConverter.ToUInt16(bytes, 0) If value16 = &hFEFF Or value16 = &hFFFE Then Return EncodingType.Utf16 End If Return EncodingType.Unknown End Function End Class ' The example displays the following output: ' Filename: .\TestFile.dat, Encoding: Unknown
Tipos de excepciones relacionados
La NotSupportedException excepción está estrechamente relacionada con otros dos tipos de excepción;
NotImplementedException.
Esta excepción se produce cuando se puede implementar un método pero no, ya sea porque el miembro se implementará en una versión posterior, el miembro no está disponible en una plataforma determinada o el miembro pertenece a una clase abstracta y una clase derivada debe proporcionar una implementación.
InvalidOperationException
Esta excepción se produce en escenarios en los que, por lo general, es posible que el objeto realice la operación solicitada y el estado del objeto determina si se puede realizar la operación.
Notas de .NET Compact Framework
Al trabajar con .NET Compact Framework y usar P/Invoke en una función nativa, se puede producir esta excepción si:
La declaración en código administrado es incorrecta.
.NET Compact Framework no admite lo que intenta hacer.
Los nombres del archivo DLL tienen un sufijo en exportación.
Si se produce una NotSupportedException excepción, compruebe:
Para cualquier infracción de las restricciones P/Invoke de .NET Compact Framework.
Algún argumento que requiera memoria previamente asignada. Si éstos existen, debe pasar una referencia a una variable existente.
Que los nombres de las funciones exportadas sean correctos. Esto se puede comprobar con DumpBin.exe.
Que no intenta pasar demasiados argumentos.
Constructores
NotSupportedException() |
Inicializa una nueva instancia de la clase NotSupportedException, estableciendo la propiedad Message de una nueva instancia en un mensaje proporcionado por el sistema que describe el error. Este mensaje tiene en cuenta la referencia cultural del sistema actual. |
NotSupportedException(SerializationInfo, StreamingContext) |
Inicializa una nueva instancia de la clase NotSupportedException con datos serializados. |
NotSupportedException(String) |
Inicializa una nueva instancia de la clase NotSupportedException con el mensaje de error especificado. |
NotSupportedException(String, Exception) |
Inicializa una nueva instancia de la clase NotSupportedException con el mensaje de error especificado y una referencia a la excepción interna que representa la causa de esta excepción. |
Propiedades
Data |
Obtiene una colección de pares clave/valor que proporciona información definida por el usuario adicional sobre la excepción. (Heredado de Exception) |
HelpLink |
Obtiene o establece un vínculo al archivo de ayuda asociado a esta excepción. (Heredado de Exception) |
HResult |
Obtiene o establece HRESULT, un valor numérico codificado que se asigna a una excepción específica. (Heredado de Exception) |
InnerException |
Obtiene la instancia Exception que produjo la excepción actual. (Heredado de Exception) |
Message |
Obtiene un mensaje que describe la excepción actual. (Heredado de Exception) |
Source |
Devuelve o establece el nombre de la aplicación o del objeto que generó el error. (Heredado de Exception) |
StackTrace |
Obtiene una representación de cadena de los marcos inmediatos en la pila de llamadas. (Heredado de Exception) |
TargetSite |
Obtiene el método que produjo la excepción actual. (Heredado de Exception) |
Métodos
Equals(Object) |
Determina si el objeto especificado es igual que el objeto actual. (Heredado de Object) |
GetBaseException() |
Cuando se invalida en una clase derivada, devuelve la clase Exception que representa la causa principal de una o más excepciones posteriores. (Heredado de Exception) |
GetHashCode() |
Sirve como la función hash predeterminada. (Heredado de Object) |
GetObjectData(SerializationInfo, StreamingContext) |
Cuando se invalida en una clase derivada, establece SerializationInfo con información sobre la excepción. (Heredado de Exception) |
GetType() |
Obtiene el tipo de tiempo de ejecución de la instancia actual. (Heredado de Exception) |
MemberwiseClone() |
Crea una copia superficial del Object actual. (Heredado de Object) |
ToString() |
Crea y devuelve una representación de cadena de la excepción actual. (Heredado de Exception) |
Eventos
SerializeObjectState |
Obsoleto.
Ocurre cuando una excepción se serializa para crear un objeto de estado de excepción que contenga datos serializados sobre la excepción. (Heredado de Exception) |