System.NotSupportedException 클래스

이 문서에서는 이 API에 대한 참조 설명서에 대한 추가 설명서를 제공합니다.

NotSupportedException 는 호출된 메서드 또는 속성에 대한 구현이 없음을 나타냅니다.

NotSupportedException 는 값이 0x80131515 HRESULT COR_E_NOTSUPPORTED를 사용합니다.

인스턴스 NotSupportedException의 초기 속성 값 목록은 생성자를 참조 NotSupportedException 하세요.

NotSupportedException 예외 throw

다음과 같은 경우 예외를 NotSupportedException throw하는 것이 좋습니다.

  • 범용 인터페이스를 구현하고 있으며 메서드 수에는 의미 있는 구현이 없습니다. 예를 들어 인터페이스를 구현하는 날짜 및 시간 형식을 IConvertible 만드는 경우 대부분의 변환에 대해 예외를 throw NotSupportedException 합니다.

  • 여러 메서드를 재정의해야 하는 추상 클래스에서 상속했습니다. 그러나 이러한 하위 집합에 대한 구현만 제공할 준비가 된 것입니다. 구현 NotSupportedException하지 않기로 결정한 메서드의 경우 .

  • 조건부로 작업을 사용하도록 설정하는 상태로 범용 형식을 정의하고 있습니다. 예를 들어 형식은 읽기 전용이거나 읽기/쓰기일 수 있습니다. 이 경우 다음을 수행합니다.

    • 개체가 읽기 전용인 경우 인스턴스 또는 인스턴스 상태를 수정하는 호출 메서드의 속성에 값을 할당하려고 하면 예외가 NotSupportedException throw됩니다.

    • 특정 기능을 사용할 수 있는지 여부를 나타내는 값을 반환 Boolean 하는 속성을 구현해야 합니다. 예를 들어 읽기 전용 또는 읽기/쓰기가 가능한 형식의 경우 읽기/쓰기 메서드 집합을 사용할 수 있는지 여부를 나타내는 속성을 구현 IsReadOnly 할 수 있습니다.

NotSupportedException 예외 처리

예외는 NotSupportedException 메서드에 구현이 없으며 메서드를 호출해서는 안 되었음을 나타냅니다. 예외를 처리해서는 안 됩니다. 대신 구현이 완전히 없는지 또는 멤버 호출이 개체의 목적(예: 읽기 전용 FileStream 개체의 메서드 호출FileStream.Write)과 일치하지 않는지 여부에 따라 예외의 원인에 따라 달라집니다.

의미 있는 방식으로 작업을 수행할 수 없으므로 구현이 제공되지 않았습니다. 추상 기본 클래스의 메서드에 대한 구현을 제공하거나 범용 인터페이스를 구현하는 개체에서 메서드를 호출하는 경우와 메서드에 의미 있는 구현이 없는 경우 일반적인 예외입니다.

예를 들어 클래스는 Convert 인터페이스를 IConvertible 구현합니다. 즉, 모든 기본 형식을 다른 모든 기본 형식으로 변환하는 메서드를 포함해야 합니다. 그러나 이러한 변환의 대부분은 불가능합니다. 따라서 메서드에 Convert.ToBoolean(DateTime) 대한 호출은 예를 들어 값 간에 변환이 가능하지 않으므로 예외를 DateTimeBoolean throw합니다NotSupportedException.

예외를 제거하려면 메서드 호출을 제거해야 합니다.

개체의 상태가 지정된 경우 메서드 호출이 지원되지 않습니다. 개체의 상태 때문에 기능을 사용할 수 없는 멤버를 호출하려고 합니다. 다음 세 가지 방법 중 하나로 예외를 제거할 수 있습니다.

  • 개체의 상태를 미리 알고 있지만 지원되지 않는 메서드 또는 속성을 호출했습니다. 이 경우 멤버 호출은 오류이며 제거할 수 있습니다.

  • 개체의 상태를 미리 알고 있지만(일반적으로 코드에서 인스턴스화했기 때문) 개체가 잘못 구성되었습니다. 다음 예제에서는 이 문제를 보여 줍니다. 읽기 전용 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.FileStream(String, FileMode, FileAccess) 문제를 해결합니다.

  • 개체의 상태를 미리 알지 못하며 개체가 특정 작업을 지원하지 않습니다. 대부분의 경우 개체는 특정 작업 집합을 지원하는지 여부를 나타내는 속성 또는 메서드를 포함해야 합니다. 개체 값을 검사 적절한 경우에만 멤버를 호출하여 예외를 제거할 수 있습니다.

    다음 예제에서는 읽기 액세스를 지원하지 않는 스트림의 시작 부분에서 읽기를 시도할 때 예외를 throw NotSupportedException 하는 메서드를 정의 DetectEncoding 합니다.

    using System;
    using System.IO;
    using System.Threading.Tasks;
    
    public class TestPropEx1
    {
        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 FileUtilities1.GetEncodingType(fs));
        }
    }
    
    public class FileUtilities1
    {
        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 Example2
        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, FileUtilities2.GetEncodingType(fs))
        End Sub
    End Module
    
    Public Class FileUtilities2
        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 = &HFEFF 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 FileUtilities2.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 FileUtilities3
        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
            End If
    
            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 = &HFEFF 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

    이 예외는 메서드를 구현할 수 있지만 멤버가 이후 버전에서 구현되거나, 멤버를 특정 플랫폼에서 사용할 수 없거나, 멤버가 추상 클래스에 속하며 파생 클래스가 구현을 제공해야 하기 때문에 throw됩니다.

  • InvalidOperationException

    이 예외는 일반적으로 개체가 요청된 작업을 수행할 수 있는 시나리오에서 throw되며 개체 상태는 작업을 수행할 수 있는지 여부를 결정합니다.

.NET Compact Framework 참고 사항

.NET Compact Framework를 사용하고 네이티브 함수에서 P/Invoke를 사용하는 경우 다음과 같은 경우 이 예외가 throw될 수 있습니다.

  • 관리 코드의 선언이 올바르지 않은 경우
  • .NET Compact Framework는 수행하려는 작업을 지원하지 않습니다.
  • 내보내기 과정에서 DLL 이름이 손상된 경우

예외가 throw되면 다음을 NotSupportedException 검사.

  • .NET Compact Framework P/Invoke 제한을 위반하는 경우
  • 메모리를 미리 할당해야 하는 인수가 있는지 여부. 이러한 인수가 있으면 기존 변수에 대한 참조를 전달해야 합니다.
  • 내보낸 함수의 이름이 올바른지 여부. DumpBin.exe 통해 확인할 수 있습니다.
  • 너무 많은 인수를 전달하려 하지 않았는지 여부