NotSupportedException 类

定义

当调用的方法不受支持时,或者当尝试读取、搜索或写入不支持所调用功能的流时引发的异常。

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
继承
NotSupportedException
继承
NotSupportedException
派生
属性

注解

NotSupportedException 指示调用的方法或属性不存在任何实现。

NotSupportedException 使用具有值0x80131515的 HRESULT COR_E_NOTSUPPORTED。

有关实例的初始属性值的列表NotSupportedException,请参阅NotSupportedException构造函数。

引发 NotSupportedException 异常

在以下情况下,可以考虑引发 NotSupportedException 异常:

  • 你正在实现常规用途接口,并且方法的数目没有有意义的实现。 例如,如果要创建实现 IConvertible 接口的日期和时间类型,则为大多数转换引发 NotSupportedException 异常。

  • 你已继承自一个抽象类,该类要求重写多个方法。 但是,你只是准备为其中一部分提供实现。 对于决定不实现的方法,可以选择引发 。NotSupportedException

  • 你正在定义具有有条件地启用操作的状态的常规用途类型。 例如,类型可以是只读类型,也可以是读写类型。 在这种情况下:

    • 如果对象是只读的,则尝试将值分配给修改实例状态的实例或调用方法的属性应引发 NotSupportedException 异常。

    • 应实现一个属性,该属性返回一个 Boolean 值,该值指示特定功能是否可用。 例如,对于可以是只读或读写的类型,可以实现一个 IsReadOnly 属性,该属性指示读写方法集是可用还是不可用。

处理 NotSupportedException 异常

异常 NotSupportedException 指示方法没有实现,不应调用此方法。 不应处理异常。 相反,应执行的操作取决于异常的原因:无论是完全缺少实现,还是成员调用与对象 (目的不一致,例如对 FileStream.Write 只读 FileStream 对象的方法的调用。

尚未提供实现,因为无法以有意义的方式执行操作。
当你对为抽象基类的方法提供实现或实现常规用途接口的对象调用方法并且该方法没有有意义的实现时,这是一个常见异常。

例如,该 Convert 类实现 IConvertible 接口,这意味着它必须包含一个方法,以便将每个基元类型转换为所有其他基元类型。 但是,许多转换都是不可能的。 因此,对方法的调用Convert.ToBoolean(DateTime)(例如)会NotSupportedException引发异常,因为一个值和值Boolean之间DateTime没有可能的转换

若要消除异常,应消除方法调用。

给定对象的状态,不支持方法调用。
您尝试调用其功能因对象状态而不可用的成员。 可以通过以下三种方式之一消除异常:

  • 事先知道对象的状态,但已调用不受支持的方法或属性。 在这种情况下,成员调用是一个错误,你可以将其消除。

  • 你事先知道对象的状态 (通常是因为代码已将其实例化) ,但对象配置错误。 以下示例演示了此问题。 它创建只读 FileStream 对象,然后尝试写入该对象。

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

    可以通过确保实例化对象支持所需的功能来消除异常。 以下示例通过向构造函数提供正确的参数FileStream.FileStream(String, FileMode, FileAccess)来解决只读FileStream对象的问题。

  • 您事先不知道对象的状态,并且该对象不支持特定操作。 在大多数情况下,该对象应包含一个属性或方法,指示它是否支持一组特定的操作。 可以通过检查对象的值并仅在适当时调用成员来消除异常。

    以下示例定义一个 DetectEncoding 方法,该方法在尝试从不支持读取访问的流开头读取时引发 NotSupportedException 异常。

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

    如果流是只读的 FileStream.CanRead ,可以通过检查属性的值并退出方法来消除异常。

       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
    

异常 NotSupportedException 与另外两种异常类型密切相关:

NotImplementedException.
当方法可以实现但不是,因为成员将在更高版本中实现,成员在特定平台上不可用,或者成员属于抽象类并且派生类必须提供实现时,将引发此异常。

InvalidOperationException
在对象执行请求的操作时,通常会引发此异常,并且对象状态确定是否可以执行该操作。

.NET Compact Framework 说明

使用 .NET Compact Framework 并在本机函数上使用 P/Invoke 时,如果出现以下情况,可能会引发此异常:

  • 托管代码中的声明不正确。

  • .NET Compact Framework 不支持你尝试执行的操作。

  • DLL 名称在导出时难以分辨。

NotSupportedException如果引发异常,请检查:

  • 对于 .NET Compact Framework P/Invoke 限制的任何冲突。

  • 任何需要预分配内存的参数。 如果存在这种情况,应传递对现有变量的引用。

  • 导出的函数的名称正确。 这可以通过 DumpBin.exe进行验证。

  • 您没有尝试传递过多的参数。

构造函数

NotSupportedException()

初始化 NotSupportedException 类的新实例,将新实例的 Message 属性设置为系统提供的描述错误的消息。 此消息会考虑当前系统区域性。

NotSupportedException(SerializationInfo, StreamingContext)

用序列化数据初始化 NotSupportedException 类的新实例。

NotSupportedException(String)

用指定的错误消息初始化 NotSupportedException 类的新实例。

NotSupportedException(String, Exception)

使用指定的错误消息和对作为此异常原因的内部异常的引用来初始化 NotSupportedException 类的新实例。

属性

Data

获取键/值对的集合,这些键/值对提供有关该异常的其他用户定义信息。

(继承自 Exception)
HelpLink

获取或设置指向与此异常关联的帮助文件链接。

(继承自 Exception)
HResult

获取或设置 HRESULT(一个分配给特定异常的编码数字值)。

(继承自 Exception)
InnerException

获取导致当前异常的 Exception 实例。

(继承自 Exception)
Message

获取描述当前异常的消息。

(继承自 Exception)
Source

获取或设置导致错误的应用程序或对象的名称。

(继承自 Exception)
StackTrace

获取调用堆栈上的即时框架字符串表示形式。

(继承自 Exception)
TargetSite

获取引发当前异常的方法。

(继承自 Exception)

方法

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetBaseException()

当在派生类中重写时,返回 Exception,它是一个或多个并发的异常的根本原因。

(继承自 Exception)
GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetObjectData(SerializationInfo, StreamingContext)

当在派生类中重写时,用关于异常的信息设置 SerializationInfo

(继承自 Exception)
GetType()

获取当前实例的运行时类型。

(继承自 Exception)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
ToString()

创建并返回当前异常的字符串表示形式。

(继承自 Exception)

事件

SerializeObjectState
已过时。

当异常被序列化用来创建包含有关该异常的徐列出数据的异常状态对象时会出现该问题。

(继承自 Exception)

适用于

另请参阅