ArgumentOutOfRangeException Klas
Definitie
Belangrijk
Bepaalde informatie heeft betrekking op een voorlopige productversie die aanzienlijk kan worden gewijzigd voordat deze wordt uitgebracht. Microsoft biedt geen enkele expliciete of impliciete garanties met betrekking tot de informatie die hier wordt verstrekt.
De uitzondering die wordt gegenereerd wanneer de waarde van een argument zich buiten het toegestane bereik van waarden bevindt, zoals gedefinieerd door de aangeroepen methode.
public ref class ArgumentOutOfRangeException : ArgumentException
public class ArgumentOutOfRangeException : ArgumentException
[System.Serializable]
public class ArgumentOutOfRangeException : ArgumentException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class ArgumentOutOfRangeException : ArgumentException
type ArgumentOutOfRangeException = class
inherit ArgumentException
[<System.Serializable>]
type ArgumentOutOfRangeException = class
inherit ArgumentException
interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ArgumentOutOfRangeException = class
inherit ArgumentException
interface ISerializable
type ArgumentOutOfRangeException = class
inherit ArgumentException
interface ISerializable
Public Class ArgumentOutOfRangeException
Inherits ArgumentException
- Overname
- Overname
- Kenmerken
- Implementeringen
Voorbeelden
In het volgende voorbeeld wordt een klasse gedefinieerd die informatie over een uitgenodigde gast bevat. Als de gast jonger is dan 21, wordt er een ArgumentOutOfRangeException uitzondering gegenereerd.
using System;
using static System.Console;
public class Program
{
public static void Main(string[] args)
{
try
{
var guest1 = new Guest("Ben", "Miller", 17);
WriteLine(guest1.GuestInfo);
}
catch (ArgumentOutOfRangeException argumentOutOfRangeException)
{
WriteLine($"Error: {argumentOutOfRangeException.Message}");
}
}
}
class Guest
{
private const int minimumRequiredAge = 21;
private string firstName;
private string lastName;
private int age;
public Guest(string firstName, string lastName, int age)
{
if (age < minimumRequiredAge)
throw new ArgumentOutOfRangeException(nameof(age), $"All guests must be {minimumRequiredAge}-years-old or older.");
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public string GuestInfo => $"{firstName} {lastName}, {age}";
}
open System
type Guest(fName: string, lName: string, age: int) =
let minimumRequiredAge = 21
do if age < minimumRequiredAge then
raise (ArgumentOutOfRangeException(nameof age, $"All guests must be {minimumRequiredAge}-years-old or older."))
member _.FirstName = fName
member _.LastName = lName
member _.GuestInfo() = $"{fName} {lName}, {age}"
try
let guest1 = Guest("Ben", "Miller", 17);
printfn $"{guest1.GuestInfo()}"
with
| :? ArgumentOutOfRangeException as e ->
printfn $"Error: {e.Message}"
Module Module1
Public Sub Main()
Try
Dim guest1 As Guest = New Guest("Ben", "Miller", 17)
Console.WriteLine(guest1.GuestInfo)
Catch outOfRange As ArgumentOutOfRangeException
Console.WriteLine("Error: {0}", outOfRange.Message)
End Try
End Sub
End Module
Class Guest
Private FirstName As String
Private LastName As String
Private Age As Integer
Public Sub New(ByVal fName As String, ByVal lName As String, ByVal age As Integer)
MyBase.New()
FirstName = fName
LastName = lName
If (age < 21) Then
Throw New ArgumentOutOfRangeException("age", "All guests must be 21-years-old or older.")
Else
age = age
End If
End Sub
Public Function GuestInfo() As String
Dim gInfo As String = (FirstName + (" " _
+ (Me.LastName + (", " + Me.Age.ToString))))
Return gInfo
End Function
End Class
Opmerkingen
Er ArgumentOutOfRangeException wordt een uitzondering gegenereerd wanneer een methode wordt aangeroepen en ten minste één van de argumenten die aan de methode worden doorgegeven, niet null is en een ongeldige waarde bevat die geen lid is van de set waarden die voor het argument worden verwacht. De ParamName eigenschap identificeert het ongeldige argument en de ActualValue eigenschap, als er een waarde aanwezig is, identificeert de ongeldige waarde.
Normaal gesproken treedt er een fout op bij ontwikkelaars ArgumentOutOfRangeException . In plaats van de uitzondering in een try/catch blok te verwerken, moet u de oorzaak van de uitzondering elimineren of, als het argument wordt geretourneerd door een methodeaanroep of invoer door de gebruiker voordat deze wordt doorgegeven aan de methode die de uitzondering genereert, moet u argumenten valideren voordat deze worden doorgegeven aan de methode.
ArgumentOutOfRangeException wordt uitgebreid gebruikt door:
Klassen in de System.Collections en System.IO naamruimten.
De Array klas.
Methoden voor het bewerken van tekenreeksen in de String klasse.
De voorwaarden waarin een ArgumentOutOfRangeException uitzondering wordt gegenereerd, zijn onder andere:
U haalt het lid van een verzameling op met het indexnummer en het indexnummer is ongeldig.
Dit is de meest voorkomende oorzaak van een ArgumentOutOfRangeException uitzondering. Normaal gesproken is het indexnummer om een van de vier redenen ongeldig:
De verzameling heeft geen leden en uw code gaat ervan uit dat dit wel het geval is. In het volgende voorbeeld wordt geprobeerd het eerste element van een verzameling op te halen dat geen elementen bevat:
using System; using System.Collections.Generic; public class Example4 { public static void Main() { var list = new List<string>(); Console.WriteLine("Number of items: {0}", list.Count); try { Console.WriteLine("The first item: '{0}'", list[0]); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.Message); } } } // The example displays the following output: // Number of items: 0 // Index was out of range. Must be non-negative and less than the size of the collection. // Parameter name: indexopen System let list = ResizeArray<string>() printfn $"Number of items: {list.Count}" try printfn $"The first item: '{list[0]}'" with | :? ArgumentOutOfRangeException as e -> printfn $"{e.Message}" // The example displays the following output: // Number of items: 0 // Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')Imports System.Collections.Generic Module Example Public Sub Main() Dim list As New List(Of String) Console.WriteLine("Number of items: {0}", list.Count) Try Console.WriteLine("The first item: '{0}'", list(0)) Catch e As ArgumentOutOfRangeException Console.WriteLine(e.Message) End Try End Sub End Module ' The example displays the following output: ' Number of items: 0 ' Index was out of range. Must be non-negative and less than the size of the collection. ' Parameter name: indexAls u de uitzondering wilt voorkomen, controleert u of de eigenschap van
Countde verzameling groter is dan nul voordat u probeert leden op te halen, zoals het volgende codefragment doet.if (list.Count > 0) Console.WriteLine("The first item: '{0}'", list[0]);if list.Count > 0 then printfn $"The first item: '{list[0]}'"If list.Count > 0 Then Console.WriteLine("The first item: '{0}'", list(0)) End IfIn sommige gevallen kan de uitzondering optreden omdat u probeert een lid toe te voegen aan een verzameling met behulp van een index die niet bestaat, in plaats van door de methode aan te roepen, zoals
Add, die voor dit doel bestaat. In het volgende voorbeeld wordt geprobeerd een element toe te voegen aan een verzameling met behulp van een niet-bestaande index in plaats van de methode aan te List<T>.Add roepen.using System; using System.Collections.Generic; public class Example13 { public static void Main() { var numbers = new List<int>(); numbers.AddRange( new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20 } ); var squares = new List<int>(); for (int ctr = 0; ctr < numbers.Count; ctr++) squares[ctr] = (int) Math.Pow(numbers[ctr], 2); } } // The example displays the following output: // 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.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) // at Example.Main()let numbers = ResizeArray<int>() numbers.AddRange [ 0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 20 ] let squares = ResizeArray<int>() for ctr = 0 to numbers.Count - 1 do squares[ctr] <- int (float numbers[ctr] ** 2) // The example displays the following output: // Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index') // at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) // at <StartupCode$argumentoutofrangeexception>.$NoElements.main@()Imports System.Collections.Generic Module Example Public Sub Main() Dim numbers As New List(Of Integer) numbers.AddRange( { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20 } ) Dim squares As New List(Of Integer) For ctr As Integer = 0 To numbers.Count - 1 squares(ctr) = CInt(numbers(ctr) ^ 2) Next End Sub End Module ' The example displays the following output: ' 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.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) ' at Example.Main()Met het volgende codefragment wordt deze fout gecorrigeerd:
var squares = new List<int>(); for (int ctr = 0; ctr < numbers.Count; ctr++) squares.Add((int) Math.Pow(numbers[ctr], 2));let squares = ResizeArray<int>() for ctr = 0 to numbers.Count - 1 do squares.Add(int (float numbers[ctr] ** 2))Dim squares As New List(Of Integer) For ctr As Integer = 0 To numbers.Count - 1 squares.Add(CInt(numbers(ctr) ^ 2)) NextU probeert een item op te halen waarvan de index negatief is. Dit gebeurt meestal omdat u een verzameling hebt gezocht naar de index van een bepaald element en u ten onrechte hebt aangenomen dat de zoekopdracht is geslaagd. In het volgende voorbeeld kan de aanroep van de List<T>.FindIndex(Predicate<T>) methode geen tekenreeks vinden die gelijk is aan 'Z' en retourneert dus -1. Dit is echter een ongeldige indexwaarde.
using System; using System.Collections.Generic; public class Example { public static void Main() { var list = new List<string>(); list.AddRange( new String[] { "A", "B", "C" } ); // Get the index of the element whose value is "Z". int index = list.FindIndex((new StringSearcher("Z")).FindEquals); try { Console.WriteLine("Index {0} contains '{1}'", index, list[index]); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.Message); } } } internal class StringSearcher { string value; public StringSearcher(string value) { this.value = value; } public bool FindEquals(string s) { return s.Equals(value, StringComparison.InvariantCulture); } } // The example displays the following output: // Index was out of range. Must be non-negative and less than the size of the collection. // Parameter name: indexopen System module StringSearcher = let findEquals (s: string) value = s.Equals(value, StringComparison.InvariantCulture) let list = ResizeArray<string>() list.AddRange [ "A"; "B"; "C" ] // Get the index of the element whose value is "Z". let index = list.FindIndex(StringSearcher.findEquals "Z") try printfn $"Index {index} contains '{list[index]}'" with | :? ArgumentOutOfRangeException as e -> printfn $"{e.Message}" // The example displays the following output: // Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')Imports System.Collections.Generic Module Example Public Sub Main() Dim list As New List(Of String) list.AddRange( { "A", "B", "C" } ) ' Get the index of the element whose value is "Z". Dim index As Integer = list.FindIndex(AddressOf (New StringSearcher("Z")).FindEquals) Try Console.WriteLine("Index {0} contains '{1}'", index, list(index)) Catch e As ArgumentOutOfRangeException Console.WriteLine(e.Message) End Try End Sub End Module Friend Class StringSearcher Dim value As String Public Sub New(value As String) Me.value = value End Sub Public Function FindEquals(s As String) As Boolean Return s.Equals(value, StringComparison.InvariantCulture) End Function End Class ' The example displays the following output: ' Index was out of range. Must be non-negative and less than the size of the collection. ' Parameter name: indexAls u de uitzondering wilt voorkomen, controleert u of de zoekopdracht is geslaagd door ervoor te zorgen dat de geretourneerde index groter is dan of gelijk is aan nul voordat u het item uit de verzameling probeert op te halen, zoals het volgende codefragment doet.
// Get the index of the element whose value is "Z". int index = list.FindIndex((new StringSearcher("Z")).FindEquals); if (index >= 0) Console.WriteLine("'Z' is found at index {0}", list[index]);// Get the index of the element whose value is "Z". let index = list.FindIndex(StringSearcher.findEquals "Z") if index >= 0 then printfn $"'Z' is found at index {list[index]}"' Get the index of the element whose value is "Z". Dim index As Integer = list.FindIndex(AddressOf (New StringSearcher("Z")).FindEquals) If index >= 0 Then Console.WriteLine("Index {0} contains '{1}'", index, list(index)) End IfU probeert een element op te halen waarvan de index gelijk is aan de waarde van de eigenschap van de verzameling
Count, zoals in het volgende voorbeeld wordt geïllustreerd.using System; using System.Collections.Generic; public class Example8 { public static void Main() { var list = new List<string>(); list.AddRange( new String[] { "A", "B", "C" } ); try { // Display the elements in the list by index. for (int ctr = 0; ctr <= list.Count; ctr++) Console.WriteLine("Index {0}: {1}", ctr, list[ctr]); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(e.Message); } } } // The example displays the following output: // Index 0: A // Index 1: B // Index 2: C // Index was out of range. Must be non-negative and less than the size of the collection. // Parameter name: indexopen System let list = ResizeArray<string>() list.AddRange [ "A"; "B"; "C" ] try // Display the elements in the list by index. for i = 0 to list.Count do printfn $"Index {i}: {list[i]}" with | :? ArgumentOutOfRangeException as e -> printfn $"{e.Message}" // The example displays the following output: // Index 0: A // Index 1: B // Index 2: C // Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')Imports System.Collections.Generic Module Example Public Sub Main() Dim list As New List(Of String) list.AddRange( { "A", "B", "C" } ) Try ' Display the elements in the list by index. For ctr As Integer = 0 To list.Count Console.WriteLine("Index {0}: {1}", ctr, list(ctr)) Next Catch e As ArgumentOutOfRangeException Console.WriteLine(e.Message) End Try End Sub End Module ' The example displays the following output: ' Index 0: A ' Index 1: B ' Index 2: C ' Index was out of range. Must be non-negative and less than the size of the collection. ' Parameter name: indexOmdat verzamelingen in .NET op nul gebaseerde indexering gebruiken, bevindt het eerste element van de verzameling zich op index 0 en bevindt het laatste element zich op index
Count- 1. U kunt de fout elimineren door ervoor te zorgen dat u het laatste element op indexCount- 1 opent, zoals de volgende code doet.// Display the elements in the list by index. for (int ctr = 0; ctr < list.Count; ctr++) Console.WriteLine("Index {0}: {1}", ctr, list[ctr]);// Display the elements in the list by index. for i = 0 to list.Count - 1 do printfn $"Index {i}: {list[i]}"' Display the elements in the list by index. For ctr As Integer = 0 To list.Count - 1 Console.WriteLine("Index {0}: {1}", ctr, list(ctr)) Next
U probeert een tekenreeksbewerking uit te voeren door een bewerkingsmethode voor tekenreeksen aan te roepen en de beginindex bestaat niet in de tekenreeks.
Overbelasting van methoden zoals String.Compare, , String.CompareOrdinalString.IndexOf, , IndexOfAny, , String.Insert, , String.LastIndexOf, String.LastIndexOfAny, of RemoveString.Substring waarmee u de beginindex van de bewerking kunt opgeven, moet de index een geldige positie binnen de tekenreeks zijn. Geldige indexen variëren van 0 tot String.Length - 1.
Er zijn vier veelvoorkomende oorzaken van deze ArgumentOutOfRangeException uitzondering:
U werkt met een lege tekenreeks of String.Empty. Omdat de String.Length eigenschap 0 retourneert, genereert elke poging om deze te manipuleren door index een ArgumentOutOfRangeException uitzondering. In het volgende voorbeeld wordt een
GetFirstCharactermethode gedefinieerd waarmee het eerste teken van een tekenreeks wordt geretourneerd. Als de tekenreeks leeg is, zoals de uiteindelijke tekenreeks die aan de methode wordt doorgegeven, genereert de methode een ArgumentOutOfRangeException uitzondering.using System; public class Example1 { public static void Main() { String[] words = { "the", "today", "tomorrow", " ", "" }; foreach (var word in words) Console.WriteLine("First character of '{0}': '{1}'", word, GetFirstCharacter(word)); } private static char GetFirstCharacter(string s) { return s[0]; } } // The example displays the following output: // First character of //the//: //t// // First character of //today//: //t// // First character of //tomorrow//: //t// // First character of // //: // // // // Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. // at Example.Main()open System let getFirstCharacter (s: string) = s[0] let words = [ "the"; "today"; "tomorrow"; " "; "" ] for word in words do printfn $"First character of '{word}': '{getFirstCharacter word}'" // The example displays the following output: // First character of 'the': 't' // First character of 'today': 't' // First character of 'tomorrow': 't' // First character of ' ': ' ' // // Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. // at <StartupCode$argumentoutofrangeexception>.$EmptyString1.main@()Module Example Public Sub Main() Dim words() As String = { "the", "today", "tomorrow", " ", "" } For Each word In words Console.WriteLine("First character of '{0}': '{1}'", word, GetFirstCharacter(word)) Next End Sub Private Function GetFirstCharacter(s As String) As Char Return s(0) End Function End Module ' The example displays the following output: ' First character of 'the': 't' ' First character of 'today': 't' ' First character of 'tomorrow': 't' ' First character of ' ': ' ' ' ' Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. ' at Example.Main()U kunt de uitzondering elimineren door te testen of de tekenreeks String.Length groter is dan nul of door de IsNullOrEmpty methode aan te roepen om ervoor te zorgen dat de tekenreeks niet
nullof leeg is. Het volgende codefragment doet het laatste. Als de tekenreeks in dit geval leeg is of leeg isnull, retourneert deGetFirstCharactermethode U+0000.static char GetFirstCharacter(string s) { if (string.IsNullOrEmpty(s)) return '\u0000'; else return s[0]; }let getFirstCharacter (s: string) = if String.IsNullOrEmpty s then '\u0000' else s[0]Function GetFirstCharacter(s As String) As Char If String.IsNullOrEmpty(s) Then Return ChrW(0) Else Return s(0) End If End FunctionU bewerkt een tekenreeks op basis van de positie van een subtekenreeks in die tekenreeks en u hebt niet kunnen bepalen of de subtekenreeks daadwerkelijk is gevonden.
In het volgende voorbeeld wordt het tweede woord van een woordgroep met twee woorden geëxtraheerd. Er wordt een ArgumentOutOfRangeException uitzondering gegenereerd als de woordgroep uit slechts één woord bestaat en dus geen ingesloten spatie bevat. Dit komt doordat de aanroep van de String.IndexOf(String) methode -1 retourneert om aan te geven dat de zoekopdracht is mislukt en deze ongeldige waarde vervolgens wordt doorgegeven aan de String.Substring(Int32) methode.
using System; public class Example17 { public static void Main() { String[] phrases = { "ocean blue", "concerned citizen", "runOnPhrase" }; foreach (var phrase in phrases) Console.WriteLine("Second word is {0}", GetSecondWord(phrase)); } static string GetSecondWord(string s) { int pos = s.IndexOf(" "); return s.Substring(pos).Trim(); } } // The example displays the following output: // Second word is blue // Second word is citizen // // Unhandled Exception: System.ArgumentOutOfRangeException: StartIndex cannot be less than zero. // Parameter name: startIndex // at System.String.Substring(Int32 startIndex, Int32 length) // at Example17.GetSecondWord(String s) // at Example17.Main()let getSecondWord (s: string) = let pos = s.IndexOf " " s.Substring(pos).Trim() let phrases = [ "ocean blue"; "concerned citizen"; "runOnPhrase" ] for phrase in phrases do printfn $"Second word is {getSecondWord phrase}" // The example displays the following output: // Second word is blue // Second word is citizen // // Unhandled Exception: System.ArgumentOutOfRangeException: StartIndex cannot be less than zero. (Parameter 'startIndex') // at System.String.Substring(Int32 startIndex, Int32 length) // at System.String.Substring(Int32 startIndex) // at NoFind1.getSecondWord(String s) // at <StartupCode$argumentoutofrangeexception>.$NoFind1.main@()Module Example Public Sub Main() Dim phrases() As String = { "ocean blue", "concerned citizen", "runOnPhrase" } For Each phrase In phrases Console.WriteLine("Second word is {0}", GetSecondWord(phrase)) Next End Sub Function GetSecondWord(s As String) As String Dim pos As Integer = s.IndexOf(" ") Return s.Substring(pos).Trim() End Function End Module ' The example displays the following output: ' Second word is blue ' Second word is citizen ' ' Unhandled Exception: System.ArgumentOutOfRangeException: StartIndex cannot be less than zero. ' Parameter name: startIndex ' at System.String.Substring(Int32 startIndex, Int32 length) ' at Example.GetSecondWord(String s) ' at Example.Main()Als u de uitzondering wilt elimineren, valideert u de waarde die wordt geretourneerd door de tekenreekszoekmethode voordat u de bewerkingsmethode voor tekenreeksen aanroept.
using System; public class Example18 { public static void Main() { String[] phrases = { "ocean blue", "concerned citizen", "runOnPhrase" }; foreach (var phrase in phrases) { string word = GetSecondWord(phrase); if (!string.IsNullOrEmpty(word)) Console.WriteLine("Second word is {0}", word); } } static string GetSecondWord(string s) { int pos = s.IndexOf(" "); if (pos >= 0) return s.Substring(pos).Trim(); else return string.Empty; } } // The example displays the following output: // Second word is blue // Second word is citizenopen System let getSecondWord (s: string) = let pos = s.IndexOf " " if pos >= 0 then s.Substring(pos).Trim() else String.Empty let phrases = [ "ocean blue"; "concerned citizen"; "runOnPhrase" ] for phrase in phrases do let word = getSecondWord phrase if not (String.IsNullOrEmpty word) then printfn $"Second word is {word}" // The example displays the following output: // Second word is blue // Second word is citizenModule Example Public Sub Main() Dim phrases() As String = { "ocean blue", "concerned citizen", "runOnPhrase" } For Each phrase In phrases Dim word As String = GetSecondWord(phrase) If Not String.IsNullOrEmpty(word) Then _ Console.WriteLine("Second word is {0}", word) Next End Sub Function GetSecondWord(s As String) As String Dim pos As Integer = s.IndexOf(" ") If pos >= 0 Return s.Substring(pos).Trim() Else Return String.Empty End If End Function End Module ' The example displays the following output: ' Second word is blue ' Second word is citizenU hebt geprobeerd een subtekenreeks te extraheren die zich buiten het bereik van de huidige tekenreeks bevindt.
Voor de methoden waarmee subtekenreeksen worden geëxtraheerd, moet u de beginpositie van de subtekenreeks opgeven en voor subtekenreeksen die niet doorgaan naar het einde van de tekenreeks, het aantal tekens in de subtekenreeks. Houd er rekening mee dat dit niet de index is van het laatste teken in de subtekenreeks.
ArgumentOutOfRangeException In dit geval wordt meestal een uitzondering gegenereerd omdat u het aantal tekens in de subtekenreeks onjuist hebt berekend. Als u een zoekmethode gebruikt, zoals String.IndexOf het identificeren van de begin- en eindposities van een subtekenreeks:
Als het teken in de eindpositie die wordt String.IndexOf geretourneerd, moet worden opgenomen in de subtekenreeks, wordt de eindpositie van de subtekenreeks gegeven door de formule
endIndex - startIndex + 1Als het teken in de eindpositie die wordt String.IndexOf geretourneerd, moet worden uitgesloten van de subtekenreeks, wordt de eindpositie van de subtekenreeks gegeven door de formule
endIndex - startIndexIn het volgende voorbeeld wordt een
FindWordsmethode gedefinieerd die gebruikmaakt van de methode voor het String.IndexOfAny(Char[], Int32) identificeren van spatietekens en leestekens in een tekenreeks en retourneert een matrix die de woorden bevat die in de tekenreeks zijn gevonden.using System; using System.Collections.Generic; public class Example19 { public static void Main() { string sentence = "This is a simple, short sentence."; Console.WriteLine("Words in '{0}':", sentence); foreach (var word in FindWords(sentence)) Console.WriteLine(" '{0}'", word); } static String[] FindWords(string s) { int start = 0, end = 0; Char[] delimiters = { ' ', '.', ',', ';', ':', '(', ')' }; var words = new List<string>(); while (end >= 0) { end = s.IndexOfAny(delimiters, start); if (end >= 0) { if (end - start > 0) words.Add(s.Substring(start, end - start)); start = end + 1; } else { if (start < s.Length - 1) words.Add(s.Substring(start)); } } return words.ToArray(); } } // The example displays the following output: // Words in 'This is a simple, short sentence.': // 'This' // 'is' // 'a' // 'simple' // 'short' // 'sentence'let findWords (s: string) = let mutable start, end' = 0, 0 let delimiters = [| ' '; '.'; ','; ';'; ':'; '('; ')' |] let words = ResizeArray<string>() while end' >= 0 do end' <- s.IndexOfAny(delimiters, start) if end' >= 0 then if end' - start > 0 then words.Add(s.Substring(start, end' - start)) start <- end' + 1 elif start < s.Length - 1 then words.Add(s.Substring start) words.ToArray() let sentence = "This is a simple, short sentence." printfn $"Words in '{sentence}':" for word in findWords sentence do printfn $" '{word}'" // The example displays the following output: // Words in 'This is a simple, short sentence.': // 'This' // 'is' // 'a' // 'simple' // 'short' // 'sentence'Imports System.Collections.Generic Module Example Public Sub Main() Dim sentence As String = "This is a simple, short sentence." Console.WriteLine("Words in '{0}':", sentence) For Each word In FindWords(sentence) Console.WriteLine(" '{0}'", word) Next End Sub Function FindWords(s As String) As String() Dim start, ending As Integer Dim delimiters() As Char = { " "c, "."c, ","c, ";"c, ":"c, "("c, ")"c } Dim words As New List(Of String)() Do While ending >= 0 ending = s.IndexOfAny(delimiters, start) If ending >= 0 If ending - start > 0 Then words.Add(s.Substring(start, ending - start)) End If start = ending + 1 Else If start < s.Length - 1 Then words.Add(s.Substring(start)) End If End If Loop Return words.ToArray() End Function End Module ' The example displays the following output: ' Words in 'This is a simple, short sentence.': ' 'This' ' 'is' ' 'a' ' 'simple' ' 'short' ' 'sentence'
U hebt een negatief getal doorgegeven aan een methode met een argument dat alleen positieve getallen en nul vereist, of u hebt een negatief getal of nul doorgegeven aan een methode met een argument dat alleen positieve getallen vereist.
Voor de Array.CreateInstance(Type, Int32, Int32, Int32) methode moet u bijvoorbeeld het aantal elementen in elke dimensie van een tweedimensionale matrix opgeven. Geldige waarden voor elke dimensie kunnen variëren van 0 tot Int32.MaxValue. Maar omdat het dimensieargument in het volgende voorbeeld een negatieve waarde heeft, genereert de methode een ArgumentOutOfRangeException uitzondering.
using System; public class Example01 { public static void Main() { int dimension1 = 10; int dimension2 = -1; try { Array arr = Array.CreateInstance(typeof(string), dimension1, dimension2); } catch (ArgumentOutOfRangeException e) { if (e.ActualValue != null) Console.WriteLine("{0} is an invalid value for {1}: ", e.ActualValue, e.ParamName); Console.WriteLine(e.Message); } } } // The example displays the following output: // Non-negative number required. // Parameter name: length2open System let dimension1 = 10 let dimension2 = -1 try let arr = Array.CreateInstance(typeof<string>, dimension1, dimension2) printfn "%A" arr with | :? ArgumentOutOfRangeException as e -> if not (isNull e.ActualValue) then printfn $"{e.ActualValue} is an invalid value for {e.ParamName}: " printfn $"{e.Message}" // The example displays the following output: // Non-negative number required. (Parameter 'length2')Module Example Public Sub Main() Dim dimension1 As Integer = 10 Dim dimension2 As Integer = -1 Try Dim arr AS Array = Array.CreateInstance(GetType(String), dimension1, dimension2) Catch e As ArgumentOutOfRangeException If e.ActualValue IsNot Nothing Then Console.WriteLine("{0} is an invalid value for {1}: ", e.ActualValue, e.ParamName) End If Console.WriteLine(e.Message) End Try End Sub End Module ' The example displays the following output: ' Non-negative number required. ' Parameter name: length2Als u de fout wilt corrigeren, moet u ervoor zorgen dat de waarde van het ongeldige argument niet-negatief is. U kunt dit doen door een geldige waarde op te geven, zoals het volgende codefragment wel doet.
int dimension1 = 10; int dimension2 = 10; Array arr = Array.CreateInstance(typeof(string), dimension1, dimension2);let dimension1 = 10 let dimension2 = 10 let arr = Array.CreateInstance(typeof<string>, dimension1, dimension2) printfn "%A" arrDim dimension1 As Integer = 10 Dim dimension2 As Integer = 10 Dim arr As Array = Array.CreateInstance(GetType(String), dimension1, dimension2)U kunt ook de invoer valideren en, als deze ongeldig is, enige actie ondernemen. In het volgende codefragment wordt een foutbericht weergegeven in plaats van de methode aan te roepen.
if (dimension1 < 0 || dimension2 < 0) { Console.WriteLine("Unable to create the array."); Console.WriteLine("Specify non-negative values for the two dimensions."); } else { arr = Array.CreateInstance(typeof(string), dimension1, dimension2); }if dimension1 < 0 || dimension2 < 0 then printfn "Unable to create the array." printfn "Specify non-negative values for the two dimensions." else let arr = Array.CreateInstance(typeof<string>, dimension1, dimension2) printfn "%A" arrIf dimension1 < 0 OrElse dimension2 < 0 Then Console.WriteLine("Unable to create the array.") Console.WriteLine("Specify non-negative values for the two dimensions.") Else arr = Array.CreateInstance(GetType(String), dimension1, dimension2) End IfEr bestaat een racevoorwaarde in een app die multithreaded is of taken bevat die asynchroon worden uitgevoerd en waarmee een matrix of verzameling wordt bijgewerkt.
In het volgende voorbeeld wordt een List<T> object gebruikt om een verzameling
Continentobjecten te vullen. Het genereert een ArgumentOutOfRangeException als het voorbeeld probeert de zeven items in de verzameling weer te geven voordat de verzameling volledig is ingevuld.using System; using System.Collections.Generic; using System.Threading; public class Continent { public string? Name { get; set; } public int Population { get; set; } public Decimal Area { get; set; } } public class Example11 { static List<Continent> continents = new List<Continent>(); static string? s_msg; public static void Main() { String[] names = { "Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America" }; // Populate the list. foreach (var name in names) { var th = new Thread(PopulateContinents); th.Start(name); } Console.WriteLine(s_msg); Console.WriteLine(); // Display the list. for (int ctr = 0; ctr < names.Length; ctr++) { var continent = continents[ctr]; Console.WriteLine("{0}: Area: {1}, Population {2}", continent.Name, continent.Population, continent.Area); } } private static void PopulateContinents(Object? obj) { string? name = obj?.ToString(); s_msg += string.Format("Adding '{0}' to the list.\n", name); var continent = new Continent(); continent.Name = name; // Sleep to simulate retrieving remaining data. Thread.Sleep(50); continents.Add(continent); } } // The example displays output like the following: // Adding //Africa// to the list. // Adding //Antarctica// to the list. // Adding //Asia// to the list. // Adding //Australia// to the list. // Adding //Europe// to the list. // Adding //North America// to the list. // Adding //South America// to the list. // // // // 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.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) // at Example.Main()open System.Threading type Continent = { Name: string Population: int Area: decimal } let continents = ResizeArray<Continent>() let mutable msg = "" let names = [ "Africa"; "Antarctica"; "Asia" "Australia"; "Europe"; "North America" "South America" ] let populateContinents obj = let name = string obj msg <- msg + $"Adding '{name}' to the list.\n" // Sleep to simulate retrieving data. Thread.Sleep 50 let continent = { Name = name Population = 0 Area = 0M } continents.Add continent // Populate the list. for name in names do let th = Thread(ParameterizedThreadStart populateContinents) th.Start name printfn $"{msg}\n" // Display the list. for i = 0 to names.Length - 1 do let continent = continents[i] printfn $"{continent.Name}: Area: {continent.Population}, Population {continent.Area}" // The example displays output like the following: // Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index') // at System.Collections.Generic.List`1.get_Item(Int32 index) // at <StartupCode$argumentoutofrangeexception>.$Race1.main@()Imports System.Collections.Generic Imports System.Threading Public Class Continent Public Property Name As String Public Property Population As Integer Public Property Area As Decimal End Class Module Example Dim continents As New List(Of Continent) Dim msg As String Public Sub Main() Dim names() As String = { "Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America" } ' Populate the list. For Each name In names Dim th As New Thread(AddressOf PopulateContinents) th.Start(name) Next Console.WriteLine(msg) Console.WriteLine() ' Display the list. For ctr As Integer = 0 To names.Length - 1 Dim continent = continents(ctr) Console.WriteLine("{0}: Area: {1}, Population {2}", continent.Name, continent.Population, continent.Area) Next End Sub Private Sub PopulateContinents(obj As Object) Dim name As String = obj.ToString() msg += String.Format("Adding '{0}' to the list.{1}", name, vbCrLf) Dim continent As New Continent() continent.Name = name ' Sleep to simulate retrieving remaining data. Thread.Sleep(50) continents.Add(continent) End Sub End Module ' The example displays output like the following: ' Adding 'Africa' to the list. ' Adding 'Antarctica' to the list. ' Adding 'Asia' to the list. ' Adding 'Australia' to the list. ' Adding 'Europe' to the list. ' Adding 'North America' to the list. ' Adding 'South America' to the list. ' ' ' ' 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.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) ' at Example.Main()In dit geval zijn er twee resources toegankelijk vanuit meerdere threads:
De
continentsverzameling. De List<T>.Add methode wordt aangeroepen vanuit meerdere threads. Bovendien gaat de hoofd- of primaire thread ervan uit dat de verzameling volledig is gevuld met zeven elementen wanneer deze de leden herhaalt.De
msgtekenreeks, die wordt samengevoegd vanuit meerdere threads.
U kunt de fout als volgt corrigeren door ervoor te zorgen dat de gedeelde status als volgt wordt geopend op een thread-veilige manier.
als uw app gebruikmaakt van een matrix- of verzamelingsobject, kunt u overwegen een threadveilige verzamelingsklasse te gebruiken, zoals de typen in de System.Collections.Concurrent naamruimte of de System.Collections.Immutable out-of-band-release.
Zorg ervoor dat de gedeelde status (dat wil gezegd resources die kunnen worden geopend door meerdere threads) op een veilige manier wordt geopend, zodat slechts één thread tegelijk exclusieve toegang heeft tot de resources. Een groot aantal klassen, zoals CountdownEvent, Interlockeden Monitor, Mutexis beschikbaar om de toegang tot resources te synchroniseren. Zie Threading voor meer informatie. Daarnaast is taalondersteuning beschikbaar via de instructie lock in C# en de SyncLock constructie in Visual Basic.
In het volgende voorbeeld worden de ArgumentOutOfRangeException en andere problemen uit het vorige voorbeeld opgelost. Het object wordt vervangen door List<T> een ConcurrentBag<T> object om ervoor te zorgen dat de toegang tot de verzameling thread-veilig is, gebruikt een CountdownEvent object om ervoor te zorgen dat de toepassingsthread alleen wordt voortgezet nadat andere threads zijn uitgevoerd en een vergrendeling gebruikt om ervoor te zorgen dat slechts één thread toegang heeft tot de
msgvariabele tegelijk.using System; using System.Collections.Concurrent; using System.Threading; public class ContinentD { public string? Name { get; set; } public int Population { get; set; } public Decimal Area { get; set; } } public class Example12 { static ConcurrentBag<ContinentD> ContinentDs = new ConcurrentBag<ContinentD>(); static CountdownEvent? gate; static string msg = string.Empty; public static void Main() { String[] names = { "Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America" }; gate = new CountdownEvent(names.Length); // Populate the list. foreach (var name in names) { var th = new Thread(PopulateContinentDs); th.Start(name); } // Display the list. gate.Wait(); Console.WriteLine(msg); Console.WriteLine(); var arr = ContinentDs.ToArray(); for (int ctr = 0; ctr < names.Length; ctr++) { var ContinentD = arr[ctr]; Console.WriteLine("{0}: Area: {1}, Population {2}", ContinentD.Name, ContinentD.Population, ContinentD.Area); } } private static void PopulateContinentDs(Object? obj) { string? name = obj?.ToString(); lock(msg) { msg += string.Format("Adding '{0}' to the list.\n", name); } var ContinentD = new ContinentD(); ContinentD.Name = name; // Sleep to simulate retrieving remaining data. Thread.Sleep(25); ContinentDs.Add(ContinentD); gate?.Signal(); } } // The example displays output like the following: // Adding 'Africa' to the list. // Adding 'Antarctica' to the list. // Adding 'Asia' to the list. // Adding 'Australia' to the list. // Adding 'Europe' to the list. // Adding 'North America' to the list. // Adding 'South America' to the list. // // // Africa: Area: 0, Population 0 // Antarctica: Area: 0, Population 0 // Asia: Area: 0, Population 0 // Australia: Area: 0, Population 0 // Europe: Area: 0, Population 0 // North America: Area: 0, Population 0 // South America: Area: 0, Population 0open System.Collections.Concurrent open System.Threading type Continent = { Name: string Population: int Area: decimal } let continents = ConcurrentBag<Continent>(); let mutable msg = "" let names = [ "Africa"; "Antarctica"; "Asia" "Australia"; "Europe"; "North America" "South America" ] let gate = new CountdownEvent(names.Length) let populateContinents obj = let name = string obj lock msg (fun () -> msg <- msg + $"Adding '{name}' to the list.\n" ) // Sleep to simulate retrieving remaining data. let continent = { Name = name Population = 0 Area = 0M } Thread.Sleep 25 continents.Add continent gate.Signal() |> ignore // Populate the list. for name in names do let th = Thread(ParameterizedThreadStart populateContinents) th.Start name // Display the list. gate.Wait(); printfn $"{msg}\n" let arr = continents.ToArray(); for i = 0 to names.Length - 1 do let continent = arr[i] printfn $"{continent.Name}: Area: {continent.Population}, Population {continent.Area}" // The example displays output like the following: // Adding 'Africa' to the list. // Adding 'Antarctica' to the list. // Adding 'Asia' to the list. // Adding 'Australia' to the list. // Adding 'Europe' to the list. // Adding 'North America' to the list. // Adding 'South America' to the list. // // // Africa: Area: 0, Population 0 // Antarctica: Area: 0, Population 0 // Asia: Area: 0, Population 0 // Australia: Area: 0, Population 0 // Europe: Area: 0, Population 0 // North America: Area: 0, Population 0 // South America: Area: 0, Population 0Imports System.Collections.Concurrent Imports System.Threading Public Class Continent Public Property Name As String Public Property Population As Integer Public Property Area As Decimal End Class Module Example Dim continents As New ConcurrentBag(Of Continent) Dim gate As CountdownEvent Dim msg As String = String.Empty Public Sub Main() Dim names() As String = { "Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America" } gate = new CountdownEvent(names.Length) ' Populate the list. For Each name In names Dim th As New Thread(AddressOf PopulateContinents) th.Start(name) Next ' Display the list. gate.Wait() Console.WriteLine(msg) Console.WriteLine() For ctr As Integer = 0 To names.Length - 1 Dim continent = continents(ctr) Console.WriteLine("{0}: Area: {1}, Population {2}", continent.Name, continent.Population, continent.Area) Next End Sub Private Sub PopulateContinents(obj As Object) Dim name As String = obj.ToString() SyncLock msg msg += String.Format("Adding '{0}' to the list.{1}", name, vbCrLf) End SyncLock Dim continent As New Continent() continent.Name = name ' Sleep to simulate retrieving remaining data. Thread.Sleep(25) continents.Add(continent) gate.Signal() End Sub End Module ' The example displays output like the following: ' Adding 'Africa' to the list. ' Adding 'Antarctica' to the list. ' Adding 'Asia' to the list. ' Adding 'Australia' to the list. ' Adding 'Europe' to the list. ' Adding 'North America' to the list. ' Adding 'South America' to the list. ' ' ' Africa: Area: 0, Population 0 ' Antarctica: Area: 0, Population 0 ' Asia: Area: 0, Population 0 ' Australia: Area: 0, Population 0 ' Europe: Area: 0, Population 0 ' North America: Area: 0, Population 0 ' South America: Area: 0, Population 0
ArgumentOutOfRangeException maakt gebruik van de HRESULT-COR_E_ARGUMENTOUTOFRANGE, met de waarde 0x80131502.
Voor een lijst van initiële eigenschapswaarden voor een exemplaar van ArgumentOutOfRangeException, zie de ArgumentOutOfRangeException-constructoren.
Constructors
| Name | Description |
|---|---|
| ArgumentOutOfRangeException() |
Initialiseert een nieuw exemplaar van de ArgumentOutOfRangeException klasse. |
| ArgumentOutOfRangeException(SerializationInfo, StreamingContext) |
Initialiseert een nieuw exemplaar van de ArgumentOutOfRangeException klasse met geserialiseerde gegevens. |
| ArgumentOutOfRangeException(String, Exception) |
Initialiseert een nieuw exemplaar van de ArgumentOutOfRangeException klasse met een opgegeven foutbericht en de uitzondering die de oorzaak van deze uitzondering is. |
| ArgumentOutOfRangeException(String, Object, String) |
Initialiseert een nieuw exemplaar van de ArgumentOutOfRangeException klasse met de parameternaam, de waarde van het argument en een opgegeven foutbericht. |
| ArgumentOutOfRangeException(String, String) |
Initialiseert een nieuw exemplaar van de ArgumentOutOfRangeException klasse met de naam van de parameter die deze uitzondering veroorzaakt en een opgegeven foutbericht. |
| ArgumentOutOfRangeException(String) |
Initialiseert een nieuw exemplaar van de ArgumentOutOfRangeException klasse met de naam van de parameter die deze uitzondering veroorzaakt. |
Eigenschappen
| Name | Description |
|---|---|
| ActualValue |
Hiermee haalt u de argumentwaarde op die deze uitzondering veroorzaakt. |
| Data |
Hiermee haalt u een verzameling sleutel-waardeparen op die aanvullende door de gebruiker gedefinieerde informatie over de uitzondering bieden. (Overgenomen van Exception) |
| HelpLink |
Hiermee haalt u een koppeling op naar het Help-bestand dat aan deze uitzondering is gekoppeld. (Overgenomen van Exception) |
| HResult |
Hiermee wordt HRESULT opgehaald of ingesteld, een gecodeerde numerieke waarde die is toegewezen aan een specifieke uitzondering. (Overgenomen van Exception) |
| InnerException |
Hiermee haalt u het Exception exemplaar op dat de huidige uitzondering heeft veroorzaakt. (Overgenomen van Exception) |
| Message |
Hiermee wordt het foutbericht en de tekenreeksweergave van de ongeldige argumentwaarde opgehaald, of alleen het foutbericht als de argumentwaarde null is. |
| ParamName |
Hiermee haalt u de naam op van de parameter die deze uitzondering veroorzaakt. (Overgenomen van ArgumentException) |
| Source |
Hiermee wordt de naam van de toepassing of het object dat de fout veroorzaakt, opgehaald of ingesteld. (Overgenomen van Exception) |
| StackTrace |
Hiermee haalt u een tekenreeksweergave van de directe frames op de aanroepstack op. (Overgenomen van Exception) |
| TargetSite |
Hiermee haalt u de methode op waarmee de huidige uitzondering wordt gegenereerd. (Overgenomen van Exception) |
Methoden
| Name | Description |
|---|---|
| Equals(Object) |
Bepaalt of het opgegeven object gelijk is aan het huidige object. (Overgenomen van Object) |
| GetBaseException() |
Wanneer deze wordt overschreven in een afgeleide klasse, retourneert u de Exception hoofdoorzaak van een of meer volgende uitzonderingen. (Overgenomen van Exception) |
| GetHashCode() |
Fungeert als de standaardhashfunctie. (Overgenomen van Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Hiermee stelt u het SerializationInfo object in met de ongeldige argumentwaarde en aanvullende informatie over uitzonderingen. |
| GetType() |
Hiermee haalt u het runtimetype van het huidige exemplaar op. (Overgenomen van Exception) |
| MemberwiseClone() |
Hiermee maakt u een ondiepe kopie van de huidige Object. (Overgenomen van Object) |
| ToString() |
Hiermee maakt en retourneert u een tekenreeksweergave van de huidige uitzondering. (Overgenomen van Exception) |
gebeurtenis
| Name | Description |
|---|---|
| SerializeObjectState |
Treedt op wanneer een uitzondering wordt geserialiseerd om een uitzonderingsstatusobject te maken dat geserialiseerde gegevens over de uitzondering bevat. (Overgenomen van Exception) |