IndexOutOfRangeException Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Исключение, возникающее при попытке получить доступ к элементу массива или коллекции с индексом, который находится за пределами его границ.
public ref class IndexOutOfRangeException sealed : Exception
public ref class IndexOutOfRangeException sealed : SystemException
public sealed class IndexOutOfRangeException : Exception
public sealed class IndexOutOfRangeException : SystemException
[System.Serializable]
public sealed class IndexOutOfRangeException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class IndexOutOfRangeException : SystemException
type IndexOutOfRangeException = class
inherit Exception
type IndexOutOfRangeException = class
inherit SystemException
[<System.Serializable>]
type IndexOutOfRangeException = class
inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type IndexOutOfRangeException = class
inherit SystemException
Public NotInheritable Class IndexOutOfRangeException
Inherits Exception
Public NotInheritable Class IndexOutOfRangeException
Inherits SystemException
- Наследование
- Наследование
- Атрибуты
Комментарии
Исключение IndexOutOfRangeException возникает, когда недопустимый индекс используется для доступа к элементу массива или коллекции, а также для чтения или записи из определенного расположения в буфере. Это исключение наследует от Exception класса, но не добавляет уникальных элементов.
Как правило, IndexOutOfRangeException исключение возникает в результате ошибки разработчика. Вместо обработки исключения следует диагностировать причину ошибки и исправить код. Наиболее распространенными причинами ошибки являются:
Забывая, что верхняя граница коллекции или отсчитываемого от нуля массива меньше, чем его количество элементов или элементов, как показано в следующем примере.
using System; using System.Collections.Generic; public class Example { public static void Main() { List<Char> characters = new List<Char>(); characters.InsertRange(0, new Char[] { 'a', 'b', 'c', 'd', 'e', 'f' } ); for (int ctr = 0; ctr <= characters.Count; ctr++) Console.Write("'{0}' ", characters[ctr]); } } // The example displays the following output: // 'a' 'b' 'c' 'd' 'e' 'f' // Unhandled Exception: // System.ArgumentOutOfRangeException: // Index was out of range. Must be non-negative and less than the size of the collection. // Parameter name: index // at Example.Main()let characters = ResizeArray() characters.InsertRange(0, [| 'a'; 'b'; 'c'; 'd'; 'e'; 'f' |]) for i = 0 to characters.Count do printf $"'{characters[i]}' " // The example displays the following output: // 'a' 'b' 'c' 'd' 'e' 'f' // Unhandled Exception: // System.ArgumentOutOfRangeException: // Index was out of range. Must be non-negative and less than the size of the collection. // Parameter name: index // at <StartupCode$fs>.main@()Imports System.Collections.Generic Module Example Public Sub Main() Dim characters As New List(Of Char)() characters.InsertRange(0, { "a"c, "b"c, "c"c, "d"c, "e"c, "f"c} ) For ctr As Integer = 0 To characters.Count Console.Write("'{0}' ", characters(ctr)) Next End Sub End Module ' The example displays the following output: ' 'a' 'b' 'c' 'd' 'e' 'f' ' Unhandled Exception: ' System.ArgumentOutOfRangeException: ' Index was out of range. Must be non-negative and less than the size of the collection. ' Parameter name: index ' at System.Collections.Generic.List`1.get_Item(Int32 index) ' at Example.Main()Чтобы исправить ошибку, можно использовать следующий код.
using System; using System.Collections.Generic; public class Example { public static void Main() { List<Char> characters = new List<Char>(); characters.InsertRange(0, new Char[] { 'a', 'b', 'c', 'd', 'e', 'f' } ); for (int ctr = 0; ctr < characters.Count; ctr++) Console.Write("'{0}' ", characters[ctr]); } } // The example displays the following output: // 'a' 'b' 'c' 'd' 'e' 'f'let characters = ResizeArray() characters.InsertRange(0, [| 'a'; 'b'; 'c'; 'd'; 'e'; 'f' |]) for i = 0 to characters.Count - 1 do printf $"'{characters[i]}' " // The example displays the following output: // 'a' 'b' 'c' 'd' 'e' 'f'Imports System.Collections.Generic Module Example Public Sub Main() Dim characters As New List(Of Char)() characters.InsertRange(0, { "a"c, "b"c, "c"c, "d"c, "e"c, "f"c} ) For ctr As Integer = 0 To characters.Count - 1 Console.Write("'{0}' ", characters(ctr)) Next End Sub End Module ' The example displays the following output: ' 'a' 'b' 'c' 'd' 'e' 'f'Кроме того, вместо итерации всех элементов массива по индексу можно использовать
foreachинструкцию (в C#),for...inинструкцию (в F#) или инструкциюFor Each(в Visual Basic).Попытка назначить элемент массива другому массиву, который не был достаточно измерен и имеет меньше элементов, чем исходный массив. В следующем примере выполняется попытка назначить последний элемент в
value1массиве тому же элементу в массивеvalue2.value2Однако массив был неправильно измерен, чтобы иметь шесть вместо семи элементов. В результате назначение создает IndexOutOfRangeException исключение.public class Example { public static void Main() { int[] values1 = { 3, 6, 9, 12, 15, 18, 21 }; int[] values2 = new int[6]; // Assign last element of the array to the new array. values2[values1.Length - 1] = values1[values1.Length - 1]; } } // The example displays the following output: // Unhandled Exception: // System.IndexOutOfRangeException: // Index was outside the bounds of the array. // at Example.Main()let values1 = [| 3; 6; 9; 12; 15; 18; 21 |] let values2 = Array.zeroCreate<int> 6 // Assign last element of the array to the new array. values2[values1.Length - 1] <- values1[values1.Length - 1]; // The example displays the following output: // Unhandled Exception: // System.IndexOutOfRangeException: // Index was outside the bounds of the array. // at <StartupCode$fs>.main@()Module Example Public Sub Main() Dim values1() As Integer = { 3, 6, 9, 12, 15, 18, 21 } Dim values2(5) As Integer ' Assign last element of the array to the new array. values2(values1.Length - 1) = values1(values1.Length - 1) End Sub End Module ' The example displays the following output: ' Unhandled Exception: ' System.IndexOutOfRangeException: ' Index was outside the bounds of the array. ' at Example.Main()Использование значения, возвращаемого методом поиска, для итерации части массива или коллекции, начиная с определенной позиции индекса. Если вы забыли проверить, найдена ли операция поиска совпадения, среда выполнения создает IndexOutOfRangeException исключение, как показано в этом примере.
using System; using System.Collections.Generic; public class Example { static List<int> numbers = new List<int>(); public static void Main() { int startValue; string[] args = Environment.GetCommandLineArgs(); if (args.Length < 2) startValue = 2; else if (!Int32.TryParse(args[1], out startValue)) startValue = 2; ShowValues(startValue); } private static void ShowValues(int startValue) { // Create a collection with numeric values. if (numbers.Count == 0) numbers.AddRange( new int[] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22} ); // Get the index of a startValue. Console.WriteLine("Displaying values greater than or equal to {0}:", startValue); int startIndex = numbers.IndexOf(startValue); // Display all numbers from startIndex on. for (int ctr = startIndex; ctr < numbers.Count; ctr++) Console.Write(" {0}", numbers[ctr]); } } // The example displays the following output if the user supplies // 7 as a command-line parameter: // Displaying values greater than or equal to 7: // // Unhandled Exception: System.ArgumentOutOfRangeException: // Index was out of range. Must be non-negative and less than the size of the collection. // Parameter name: index // at System.Collections.Generic.List`1.get_Item(Int32 index) // at Example.ShowValues(Int32 startValue) // at Example.Main()open System let numbers = ResizeArray() let showValues startValue = // Create a collection with numeric values. if numbers.Count = 0 then numbers.AddRange [| 2..2..22 |] // Get the index of a startValue. printfn $"Displaying values greater than or equal to {startValue}:" let startIndex = numbers.IndexOf startValue // Display all numbers from startIndex on. for i = startIndex to numbers.Count - 1 do printf $" {numbers[i]}" let startValue = let args = Environment.GetCommandLineArgs() if args.Length < 2 then 2 else match Int32.TryParse args[1] with | true, v -> v | _ -> 2 showValues startValue // The example displays the following output if the user supplies // 7 as a command-line parameter: // Displaying values greater than or equal to 7: // // Unhandled Exception: System.ArgumentOutOfRangeException: // Index was out of range. Must be non-negative and less than the size of the collection. // Parameter name: index // at System.Collections.Generic.List`1.get_Item(Int32 index) // at Example.ShowValues(Int32 startValue) // at <StartupCode$fs>.main@()Imports System.Collections.Generic Module Example Dim numbers As New List(Of Integer) Public Sub Main() Dim startValue As Integer Dim args() As String = Environment.GetCommandLineArgs() If args.Length < 2 Then startValue = 2 Else If Not Int32.TryParse(args(1), startValue) Then startValue = 2 End If End If ShowValues(startValue) End Sub Private Sub ShowValues(startValue As Integer) ' Create a collection with numeric values. If numbers.Count = 0 Then numbers.AddRange( { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22} ) End If ' Get the index of a particular number, in this case 7. Console.WriteLine("Displaying values greater than or equal to {0}:", startValue) Dim startIndex As Integer = numbers.IndexOf(startValue) ' Display all numbers from startIndex on. For ctr As Integer = startIndex To numbers.Count - 1 Console.Write(" {0}", numbers(ctr)) Next End Sub End Module ' The example displays the following output if the user supplies ' 7 as a command-line parameter: ' Displaying values greater than or equal to 7: ' ' Unhandled Exception: System.ArgumentOutOfRangeException: ' Index was out of range. Must be non-negative and less than the size of the collection. ' Parameter name: index ' at System.Collections.Generic.List`1.get_Item(Int32 index) ' at Example.ShowValues(Int32 startValue) ' at Example.Main()В этом случае List<T>.IndexOf метод возвращает значение -1, которое является недопустимым значением индекса, если не удается найти совпадение. Чтобы исправить эту ошибку, проверьте возвращаемое значение метода поиска перед итерированием массива, как показано в этом примере.
using System; using System.Collections.Generic; public class Example { static List<int> numbers = new List<int>(); public static void Main() { int startValue; string[] args = Environment.GetCommandLineArgs(); if (args.Length < 2) startValue = 2; else if (!Int32.TryParse(args[1], out startValue)) startValue = 2; ShowValues(startValue); } private static void ShowValues(int startValue) { // Create a collection with numeric values. if (numbers.Count == 0) numbers.AddRange( new int[] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22} ); // Get the index of startValue. int startIndex = numbers.IndexOf(startValue); if (startIndex < 0) { Console.WriteLine("Unable to find {0} in the collection.", startValue); } else { // Display all numbers from startIndex on. Console.WriteLine("Displaying values greater than or equal to {0}:", startValue); for (int ctr = startIndex; ctr < numbers.Count; ctr++) Console.Write(" {0}", numbers[ctr]); } } } // The example displays the following output if the user supplies // 7 as a command-line parameter: // Unable to find 7 in the collection.open System open System.Collections.Generic let numbers = new List<int>() let showValues startValue = // Create a collection with numeric values. if numbers.Count = 0 then numbers.AddRange [| 2..2..22 |] // Get the index of startValue. let startIndex = numbers.IndexOf startValue if startIndex < 0 then printfn $"Unable to find {startValue} in the collection." else // Display all numbers from startIndex on. printfn $"Displaying values greater than or equal to {startValue}:" for i = startIndex to numbers.Count - 1 do printf $" {numbers[i]}" let startValue = let args = Environment.GetCommandLineArgs() if args.Length < 2 then 2 else match Int32.TryParse args[1] with | true, v -> v | _ -> 2 showValues startValue // The example displays the following output if the user supplies // 7 as a command-line parameter: // Unable to find 7 in the collection.Imports System.Collections.Generic Module Example Dim numbers As New List(Of Integer) Public Sub Main() Dim startValue As Integer Dim args() As String = Environment.GetCommandLineArgs() If args.Length < 2 Then startValue = 2 Else If Not Int32.TryParse(args(1), startValue) Then startValue = 2 End If End If ShowValues(startValue) End Sub Private Sub ShowValues(startValue As Integer) ' Create a collection with numeric values. If numbers.Count = 0 Then numbers.AddRange( { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22} ) End If ' Get the index of startValue. Dim startIndex As Integer = numbers.IndexOf(startValue) If startIndex < 0 Then Console.WriteLine("Unable to find {0} in the collection.", startValue) Else ' Display all numbers from startIndex on. Console.WriteLine("Displaying values greater than or equal to {0}:", startValue) For ctr As Integer = startIndex To numbers.Count - 1 Console.Write(" {0}", numbers(ctr)) Next End If End Sub End Module ' The example displays the following output if the user supplies ' Unable to find 7 in the collection.Попытка использовать или перечислить результирующий набор, коллекцию или массив, возвращаемый запросом, не проверяя, имеет ли возвращенный объект допустимые данные.
С помощью вычисляемого значения для определения начального индекса, конечного индекса или числа элементов, которые необходимо итерировать. Если результат вычисления непредвиден, это может привести к исключению IndexOutOfRangeException . Необходимо проверить логику программы при вычислении значения индекса и проверить его перед итерированием массива или коллекции. Следующие условия должны быть верными; IndexOutOfRangeException в противном случае создается исключение:
Начальный индекс должен быть больше или равен Array.GetLowerBound измерению массива, который требуется выполнить итерацию, или больше или равен 0 для коллекции.
Конечный индекс не может превышать Array.GetUpperBound измерение массива, который требуется выполнить итерацию, или не может быть больше или равно
Countсвойству коллекции.Следующее уравнение должно иметь значение true для измерения массива, который требуется выполнить итерацию:
start_index >= lower_bound And start_index + items_to_iterate - 1 <= upper_boundДля коллекции должно быть верно следующее уравнение:
start_index >= 0 And start_index + items_to_iterate <= CountПодсказка
Начальный индекс массива или коллекции никогда не может быть отрицательным числом.
Предположим, что массив должен быть отсчитывается от нуля. Массивы, которые не основаны на нулях, могут быть созданы Array.CreateInstance(Type, Int32[], Int32[]) методом и могут быть возвращены COM-взаимодействием, хотя они не соответствуют CLS. В следующем примере показано, что возникает IndexOutOfRangeException при попытке итерации ненулевых массивов, созданных методом Array.CreateInstance(Type, Int32[], Int32[]) .
using System; public class Example { public static void Main() { Array values = Array.CreateInstance(typeof(int), new int[] { 10 }, new int[] { 1 }); int value = 2; // Assign values. for (int ctr = 0; ctr < values.Length; ctr++) { values.SetValue(value, ctr); value *= 2; } // Display values. for (int ctr = 0; ctr < values.Length; ctr++) Console.Write("{0} ", values.GetValue(ctr)); } } // The example displays the following output: // Unhandled Exception: // System.IndexOutOfRangeException: Index was outside the bounds of the array. // at System.Array.InternalGetReference(Void* elemRef, Int32 rank, Int32* pIndices) // at System.Array.SetValue(Object value, Int32 index) // at Example.Main()open System let values = Array.CreateInstance(typeof<int>, [| 10 |], [| 1 |]) let mutable value = 2 // Assign values. for i = 0 to values.Length - 1 do values.SetValue(value, i) value <- value * 2 // Display values. for i = 0 to values.Length - 1 do printf $"{values.GetValue i} " // The example displays the following output: // Unhandled Exception: // System.IndexOutOfRangeException: Index was outside the bounds of the array. // at System.Array.InternalGetReference(Void* elemRef, Int32 rank, Int32* pIndices) // at System.Array.SetValue(Object value, Int32 index) // at <StartupCode$fs>.main@()Module Example Public Sub Main() Dim values = Array.CreateInstance(GetType(Integer), { 10 }, { 1 }) Dim value As Integer = 2 ' Assign values. For ctr As Integer = 0 To values.Length - 1 values(ctr) = value value *= 2 Next ' Display values. For ctr As Integer = 0 To values.Length - 1 Console.Write("{0} ", values(ctr)) Next End Sub End Module ' The example displays the following output: ' Unhandled Exception: ' System.IndexOutOfRangeException: Index was outside the bounds of the array. ' at System.Array.InternalGetReference(Void* elemRef, Int32 rank, Int32* pIndices) ' at System.Array.SetValue(Object value, Int32 index) ' at Microsoft.VisualBasic.CompilerServices.NewLateBinding.ObjectLateIndexSetComplex(Obje ' ct Instance, Object[] Arguments, String[] ArgumentNames, Boolean OptimisticSet, Boolean RV ' alueBase) ' at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexSet(Object Instance, ' Object[] Arguments, String[] ArgumentNames) ' at Example.Main()Чтобы исправить ошибку, как это делается в следующем примере, можно вызвать GetLowerBound метод вместо предположения о начальном индексе массива.
using System; public class Example { public static void Main() { Array values = Array.CreateInstance(typeof(int), new int[] { 10 }, new int[] { 1 }); int value = 2; // Assign values. for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++) { values.SetValue(value, ctr); value *= 2; } // Display values. for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++) Console.Write("{0} ", values.GetValue(ctr)); } } // The example displays the following output: // 2 4 8 16 32 64 128 256 512 1024open System let values = Array.CreateInstance(typeof<int>, [| 10 |], [| 1 |]) let mutable value = 2 // Assign values. for i = values.GetLowerBound 0 to values.GetUpperBound 0 do values.SetValue(value, i) value <- value * 2 // Display values. for i = values.GetLowerBound 0 to values.GetUpperBound 0 do printf $"{values.GetValue i} " // The example displays the following output: // 2 4 8 16 32 64 128 256 512 1024Module Example Public Sub Main() Dim values = Array.CreateInstance(GetType(Integer), { 10 }, { 1 }) Dim value As Integer = 2 ' Assign values. For ctr As Integer = values.GetLowerBound(0) To values.GetUpperBound(0) values(ctr) = value value *= 2 Next ' Display values. For ctr As Integer = values.GetLowerBound(0) To values.GetUpperBound(0) Console.Write("{0} ", values(ctr)) Next End Sub End Module ' The example displays the following output: ' 2 4 8 16 32 64 128 256 512 1024Обратите внимание, что при вызове GetLowerBound метода для получения начального индекса массива также следует вызвать Array.GetUpperBound(Int32) метод, чтобы получить его конечный индекс.
Запутать индекс и значение по указанному индексу в числовом массиве или коллекции. Эта проблема обычно возникает при использовании инструкции
foreach(в C#),for...inинструкции (в F#) илиFor Eachинструкции (в Visual Basic). В следующем примере показана проблема.using System; public class Example { public static void Main() { // Generate array of random values. int[] values = PopulateArray(5, 10); // Display each element in the array. foreach (var value in values) Console.Write("{0} ", values[value]); } private static int[] PopulateArray(int items, int maxValue) { int[] values = new int[items]; Random rnd = new Random(); for (int ctr = 0; ctr < items; ctr++) values[ctr] = rnd.Next(0, maxValue + 1); return values; } } // The example displays output like the following: // 6 4 4 // Unhandled Exception: System.IndexOutOfRangeException: // Index was outside the bounds of the array. // at Example.Main()open System let populateArray items maxValue = let rnd = Random() [| for i = 0 to items - 1 do rnd.Next(0, maxValue + 1) |] // Generate array of random values. let values = populateArray 5 10 // Display each element in the array. for value in values do printf $"{values[value]} " // The example displays output like the following: // 6 4 4 // Unhandled Exception: System.IndexOutOfRangeException: // Index was outside the bounds of the array. // at <StartupCode$fs>.main@()Module Example Public Sub Main() ' Generate array of random values. Dim values() As Integer = PopulateArray(5, 10) ' Display each element in the array. For Each value In values Console.Write("{0} ", values(value)) Next End Sub Private Function PopulateArray(items As Integer, maxValue As Integer) As Integer() Dim values(items - 1) As Integer Dim rnd As New Random() For ctr As Integer = 0 To items - 1 values(ctr) = rnd.Next(0, maxValue + 1) Next Return values End Function End Module ' The example displays output like the following: ' 6 4 4 ' Unhandled Exception: System.IndexOutOfRangeException: ' Index was outside the bounds of the array. ' at Example.Main()Конструкция итерации возвращает каждое значение в массиве или коллекции, а не его индекс. Чтобы исключить исключение, используйте этот код.
using System; public class Example { public static void Main() { // Generate array of random values. int[] values = PopulateArray(5, 10); // Display each element in the array. foreach (var value in values) Console.Write("{0} ", value); } private static int[] PopulateArray(int items, int maxValue) { int[] values = new int[items]; Random rnd = new Random(); for (int ctr = 0; ctr < items; ctr++) values[ctr] = rnd.Next(0, maxValue + 1); return values; } } // The example displays output like the following: // 10 6 7 5 8open System let populateArray items maxValue = let rnd = Random() [| for i = 0 to items - 1 do rnd.Next(0, maxValue + 1) |] // Generate array of random values. let values = populateArray 5 10 // Display each element in the array. for value in values do printf $"{value} " // The example displays output like the following: // 10 6 7 5 8Module Example Public Sub Main() ' Generate array of random values. Dim values() As Integer = PopulateArray(5, 10) ' Display each element in the array. For Each value In values Console.Write("{0} ", value) Next End Sub Private Function PopulateArray(items As Integer, maxValue As Integer) As Integer() Dim values(items - 1) As Integer Dim rnd As New Random() For ctr As Integer = 0 To items - 1 values(ctr) = rnd.Next(0, maxValue + 1) Next Return values End Function End Module ' The example displays output like the following: ' 10 6 7 5 8Указание недопустимого имени столбца свойству DataView.Sort .
Нарушение безопасности потоков. Такие операции, как чтение из одного объекта, запись в один и тот же StreamReaderStreamWriter объект из нескольких потоков или перечисление объектов в Hashtable разных потоках может вызвать, IndexOutOfRangeException если объект не имеет доступа к потокобезопасным способом. Обычно это исключение является периодическим, так как оно зависит от состояния расы.
Использование жестко закодированных значений индекса для управления массивом, скорее всего, вызовет исключение, если значение индекса неверно или недопустимо, или если размер массива является непредвиденным. Чтобы предотвратить исключение IndexOutOfRangeException , можно сделать следующее:
Выполните итерацию элементов массива с помощью инструкции foreach (в C#), для ... оператор (в F#) или for Each... Следующая конструкция (в Visual Basic) вместо итерации элементов по индексу.
Итерация элементов по индексу, начиная с индекса, возвращаемого Array.GetLowerBound методом, и заканчивая индексом, возвращаемым методом Array.GetUpperBound .
Если вы назначаете элементы в одном массиве другому, убедитесь, что целевой массив имеет по крайней мере столько элементов, сколько исходный массив, сравнивая их Array.Length свойства.
Список начальных значений свойств для экземпляра IndexOutOfRangeExceptionсм. в конструкторах IndexOutOfRangeException.
Ниже приведены инструкции IndexOutOfRangeExceptionпо промежуточному языку (IL):
ldelem.<Тип>
ldelema
stelem.<Тип>
IndexOutOfRangeException использует COR_E_INDEXOUTOFRANGE HRESULT, которая имеет значение 0x80131508.
Конструкторы
| Имя | Описание |
|---|---|
| IndexOutOfRangeException() |
Инициализирует новый экземпляр класса IndexOutOfRangeException. |
| IndexOutOfRangeException(String, Exception) |
Инициализирует новый экземпляр IndexOutOfRangeException класса с указанным сообщением об ошибке и ссылкой на внутреннее исключение, которое является причиной этого исключения. |
| IndexOutOfRangeException(String) |
Инициализирует новый экземпляр IndexOutOfRangeException класса с указанным сообщением об ошибке. |
Свойства
| Имя | Описание |
|---|---|
| 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) |