ArgumentOutOfRangeException 類別

定義

當引數值超出叫用方法所定義之值的容許範圍時,所擲回的例外狀況。The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.

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
type ArgumentOutOfRangeException = class
    inherit ArgumentException
    interface ISerializable
[<System.Serializable>]
type ArgumentOutOfRangeException = class
    inherit ArgumentException
    interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ArgumentOutOfRangeException = class
    inherit ArgumentException
    interface ISerializable
Public Class ArgumentOutOfRangeException
Inherits ArgumentException
繼承
ArgumentOutOfRangeException
繼承
ArgumentOutOfRangeException
屬性
實作

範例

下列範例會定義一個類別,以包含受邀來賓的相關資訊。The following example defines a class to contain information about an invited guest. 如果來賓小於21,則會擲回 ArgumentOutOfRangeException 例外狀況。If the guest is younger than 21, an ArgumentOutOfRangeException exception is thrown.

using System;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Guest guest1 = new Guest("Ben", "Miller", 17);
            Console.WriteLine(guest1.GuestInfo());
        }
        catch (ArgumentOutOfRangeException outOfRange)
        {

            Console.WriteLine("Error: {0}", outOfRange.Message);
        }
    }
}

class Guest
{
    private string FirstName;
    private string LastName;
    private int Age;

    public Guest(string fName, string lName, int age)
    {
        FirstName = fName;
        LastName = lName;
        if (age < 21)
            throw new ArgumentOutOfRangeException("age","All guests must be 21-years-old or older.");
        else
            Age = age;
    }

    public string GuestInfo()
    {
        string gInfo = FirstName + " " + LastName + ", " + Age.ToString();
        return(gInfo);
    }
}
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

備註

ArgumentOutOfRangeException當方法被叫用,且至少有一個傳遞給方法的引數不是 null ,而且包含的值不是引數預期值集的成員時,就會擲回例外狀況。An ArgumentOutOfRangeException exception is thrown when a method is invoked and at least one of the arguments passed to the method is not null and contains an invalid value that is not a member of the set of values expected for the argument. ParamName屬性會識別不正確引數,而 ActualValue 如果有值,屬性會識別不正確值。The ParamName property identifies the invalid argument, and the ActualValue property, if a value is present, identifies the invalid value.

通常是 ArgumentOutOfRangeException 來自開發人員錯誤的結果。Typically, an ArgumentOutOfRangeException results from developer error. 您應該排除例外狀況的原因,而不是在傳遞給擲回例外狀況的方法之前,由方法呼叫所傳回的引數或使用者輸入,而不是處理區塊中的例外狀況 try / catch ,您應該先驗證引數,再將其傳遞給方法。Instead of handling the exception in a try/catch block, you should eliminate the cause of the exception or, if the argument is returned by a method call or input by the user before being passed to the method that throws the exception, you should validate arguments before passing them to the method.

ArgumentOutOfRangeException 廣泛消費者:ArgumentOutOfRangeException is used extensively by:

擲回例外狀況的條件 ArgumentOutOfRangeException 包括下列各項:The conditions in which an ArgumentOutOfRangeException exception is thrown include the following:

  • 您正在依索引編號來抓取集合的成員,而且索引編號無效。You are retrieving the member of a collection by its index number, and the index number is invalid.

    這是最常見的例外狀況原因 ArgumentOutOfRangeExceptionThis is the most common cause of an ArgumentOutOfRangeException exception. 一般來說,索引編號不正確原因有四個:Typically, the index number is invalid for one of four reasons:

    1. 集合沒有成員,而您的程式碼假設它有。The collection has no members, and your code assumes that it does. 下列範例會嘗試取出沒有元素之集合的第一個元素:The following example attempts to retrieve the first element of a collection that has no elements:

      using System;
      using System.Collections.Generic;
      
      public class Example
      {
         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: 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: index
      

      若要避免這個例外狀況,請先檢查集合的 Count 屬性是否大於零,再嘗試抓取任何成員,如下列程式碼片段所示。To prevent the exception, check whether the collection's Count property is greater than zero before attempting to retrieve any members, as the following code fragment does.

      if (list.Count > 0)
         Console.WriteLine("The first item: '{0}'", list[0]);
      
      If list.Count > 0 Then
         Console.WriteLine("The first item: '{0}'", list(0))
      End If
      
    2. 在某些情況下,可能會發生例外狀況,是因為您嘗試使用不存在的索引來將成員新增至集合,而不是呼叫 Add 存在於此目的的方法(例如)。In some cases, the exception may occur because you are attempting to add a member to a collection by using an index that does not exist, rather than by calling the method, such as Add, that exists for this purpose. 下列範例會嘗試使用不存在的索引,而不是呼叫方法,將專案加入至集合 List<T>.AddThe following example attempts to add an element to a collection by using a non-existent index rather than calling the List<T>.Add method.

      using System;
      using System.Collections.Generic;
      
      public class Example
      {
         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()
      
      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()
      

      下列程式碼片段會更正此錯誤:The following code fragment corrects this error:

      var squares = new List<int>();
      for (int ctr = 0; ctr < numbers.Count; ctr++)
         squares.Add((int) Math.Pow(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)) 
      Next
      
    3. 您正在嘗試取出索引為負數的專案。You're attempting to retrieve an item whose index is negative. 發生這種情況的原因通常是因為您已在集合中搜尋特定元素的索引,並已錯誤地假設搜尋成功。This usually occurs because you've searched a collection for the index of a particular element and have erroneously assumed that the search is successful. 在下列範例中,方法的呼叫 List<T>.FindIndex(Predicate<T>) 無法找到等於 "Z" 的字串,因此會傳回-1。In the following example, the call to the List<T>.FindIndex(Predicate<T>) method fails to find a string equal to "Z" and so returns -1. 不過,這是不正確索引值。However, this is an invalid index value.

      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: 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: index
      

      若要避免這個例外狀況,請在嘗試從集合中取得專案之前,確認傳回的索引大於或等於零,以檢查搜尋是否成功,如下列程式碼片段所示。To prevent the exception, check that the search is successful by making sure that the returned index is greater than or equal to zero before attempting to retrieve the item from the collection, as the following code fragment does.

      // 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".
      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 If
      
    4. 您正在嘗試取出索引等於集合屬性值的元素 Count ,如下列範例所示。You're attempting to retrieve an element whose index is equal to the value of the collection's Count property, as the following example illustrates.

      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" } );
            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: 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: index
      

      由於 .NET 中的集合會使用以零為起始的索引,因此集合的第一個元素位於索引0,而最後一個元素位於索引 Count 1。Because collections in .NET use zero-based indexing, the first element of the collection is at index 0, and the last element is at index Count - 1. 您可以藉由確定存取位於索引1的最後一個元素來消除錯誤 Count ,如下列程式碼所示。You can eliminate the error by ensuring that you access the last element at index Count - 1, as the following code does.

      // 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 ctr As Integer = 0 To list.Count - 1 
         Console.WriteLine("Index {0}: {1}", ctr, list(ctr)) 
      Next   
      
  • 您正在嘗試透過呼叫字串操作方法來執行字串作業,而且起始索引不存在於字串中。You are attempting to perform a string operation by calling a string manipulation method, and the starting index does not exist in the string.

    方法的多載(例如、、、、、、、或),可 String.Compare String.CompareOrdinal String.IndexOf IndexOfAny String.Insert String.LastIndexOf String.LastIndexOfAny Remove String.Substring 讓您指定作業的開始索引,要求索引必須是字串中的有效位置。Overloads of methods such as such as String.Compare, String.CompareOrdinal, String.IndexOf, IndexOfAny, String.Insert, String.LastIndexOf, String.LastIndexOfAny, Remove, or String.Substring that allow you to specify the starting index of the operation require that the index be a valid position within the string. 有效的索引範圍從0到 String.Length -1。Valid indexes range from 0 to String.Length - 1.

    此例外狀況有四個常見的原因 ArgumentOutOfRangeExceptionThere are four common causes of this ArgumentOutOfRangeException exception:

    1. 您正在使用空字串或 String.EmptyYou are working with an empty string, or String.Empty. 因為它的 String.Length 屬性會傳回0,所以任何依索引進行操作的嘗試都會擲回 ArgumentOutOfRangeException 例外狀況。Because its String.Length property returns 0, any attempt to manipulate it by index throws an ArgumentOutOfRangeException exception. 下列範例定義的 GetFirstCharacter 方法會傳回字串的第一個字元。The following example, defines a GetFirstCharacter method that returns the first character of a string. 如果字串是空的,而且傳遞給方法的最終字串為,則方法會擲回 ArgumentOutOfRangeException 例外狀況。If the string is empty, as the final string passed to the method is, the method throws an ArgumentOutOfRangeException exception.

      using System;
      
      public class Example
      {
         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()
      
      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()
      

      您可以藉由測試字串的值是否 String.Length 大於零,或藉由呼叫 IsNullOrEmpty 方法來確定字串不是或空白,來消除例外狀況 nullYou can eliminate the exception by testing whether the string's String.Length is greater than zero or by calling the IsNullOrEmpty method to ensure that the string is not null or empty. 下列程式碼片段會執行後者。The following code fragment does the latter. 在此情況下,如果字串是 null 或空白,則 GetFirstCharacter 方法會傳回 U + 0000。In this case, if the string is null or empty, the GetFirstCharacter method returns U+0000.

      static char GetFirstCharacter(String s)
      {
         if (String.IsNullOrEmpty(s))
            return '\u0000';
         else
            return s[0];
      }
      
      Function GetFirstCharacter(s As String) As Char
         If String.IsNullOrEmpty(s) Then 
            Return ChrW(0)
         Else   
            Return s(0)
         End If   
      End Function
      
    2. 您要根據該字串內子字串的位置來操作字串,但無法判斷是否真的找到子字串。You're manipulating a string based on the position of a substring within that string, and you've failed to determine whether the substring was actually found.

      下列範例會將兩個單字片語的第二個字組解壓縮。The following example extracts the second word of a two-word phrase. ArgumentOutOfRangeException如果片語只包含一個單字,因此不包含內嵌空白字元,則會擲回例外狀況。It throws an ArgumentOutOfRangeException exception if the phrase consists of only one word, and therefore does not contain an embedded space character. 發生這種情況是因為呼叫 String.IndexOf(String) 方法會傳回-1 來表示搜尋失敗,而這個無效值接著會傳遞給 String.Substring(Int32) 方法。This occurs because the call to the String.IndexOf(String) method returns -1 to indicate that the search failed, and this invalid value is then passed to the String.Substring(Int32) method.

      using System;
      
      public class Example
      {
         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 Example.GetSecondWord(String s)
      //       at Example.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()
      

      若要排除例外狀況,請先驗證字串搜尋方法所傳回的值,再呼叫字串操作方法。To eliminate the exception, validate the value returned by the string search method before calling the string manipulation method.

      using System;
      
      public class Example
      {
         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 citizen
      
      Module 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 citizen
      
    3. 您已嘗試解壓縮目前字串範圍之外的子字串。You've attempted to extract a substring that is outside the range of the current string.

      將子字串解壓縮的方法都需要您指定子字串的起始位置,以及針對不繼續到字串結尾的子字串,子字串中的字元數。The methods that extract substrings all require that you specify the starting position of the substring and, for substrings that do not continue to the end of the string, the number of characters in the substring. 請注意,這不是子字串中最後一個字元的 索引Note that this is not the index of the last character in the substring.

      ArgumentOutOfRangeException在此情況下,通常會擲回例外狀況,因為您不正確地計運算元字串中的字元數。An ArgumentOutOfRangeException exception is typically thrown in this case because you've incorrectly calculated the number of characters in the substring. 如果您使用類似的搜尋方法 String.IndexOf 來識別子字串的開始和結束位置:If you are using a search method like String.IndexOf to identify the starting and ending positions of a substring:

      • 如果所傳回之結束位置中的字元 String.IndexOf 要包含在子字串中,則會由公式指定子字串的結束位置。If the character in the ending position returned by String.IndexOf is to be included in the substring, the ending position of the substring is given by the formula

        endIndex - startIndex + 1
        
      • 如果所傳回之結束位置中的字元 String.IndexOf 要從子字串排除,則會由公式指定子字串的結束位置。If the character in the ending position returned by String.IndexOf is to be excluded from the substring, the ending position of the substring is given by the formula

        endIndex - startIndex
        

        下列範例會定義一個 FindWords 方法,此方法會使用 String.IndexOfAny(Char[], Int32) 方法來識別字串中的空白字元和標點符號,並傳回包含在字串中找到之單字的陣列。The following example defines a FindWords method that uses the String.IndexOfAny(Char[], Int32) method to identify space characters and punctuation marks in a string and returns an array that contains the words found in the string.

        using System;
        using System.Collections.Generic;
        
        public class Example
        {
           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'
        
        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'
        
  • 您已使用只需要正數和零的引數,將負數傳遞給方法,或您已將負數或零傳遞給方法,而該方法具有只需要正數的引數。You have passed a negative number to a method with an argument that requires only positive numbers and zero, or you have passed either a negative number or zero to a method with an argument that requires only positive numbers.

    例如,方法會 Array.CreateInstance(Type, Int32, Int32, Int32) 要求您在二維陣列的每個維度中指定專案數; 每個維度的有效值範圍可以從0到 Int32.MaxValueFor example, the Array.CreateInstance(Type, Int32, Int32, Int32) method requires that you specify the number of elements in each dimension of a two-dimensional array; valid values for each dimension can range from 0 to Int32.MaxValue. 但因為下列範例中的 dimension 引數有負值,所以方法會擲回 ArgumentOutOfRangeException 例外狀況。But because the dimension argument in the following example has a negative value, the method throws an ArgumentOutOfRangeException exception.

    using System;
    
    public class Example
    {
       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: 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: length2
    

    若要更正錯誤,請確定無效引數的值為非負數。To correct the error, ensure that the value of the invalid argument is non-negative. 若要這麼做,您可以提供有效的值,如下列程式碼片段所示。You can do this by providing a valid value, as the following code fragment does.

    int dimension1 = 10;
    int dimension2 = 10;
    Array arr = Array.CreateInstance(typeof(String),
                                     dimension1, dimension2);
    
    Dim dimension1 As Integer = 10
    Dim dimension2 As Integer = 10
    Dim arr As Array = Array.CreateInstance(GetType(String), 
                                            dimension1, dimension2)   
    

    您也可以驗證輸入,如果無效,則採取一些動作。You can also validate the input and, if it is invalid, take some action. 下列程式碼片段會顯示錯誤訊息,而不是呼叫方法。The following code fragment displays an error message instead of calling the method.

    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 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 If
    
  • 競爭條件存在於具有多執行緒的應用程式中,或具有以非同步方式執行,且會更新陣列或集合的工作。A race condition exists in an app that is multithreaded or has tasks that execute asynchronously and that updates an array or collection.

    下列範例會使用 List<T> 物件來填入物件的集合 ContinentThe following example uses a List<T> object to populate a collection of Continent objects. ArgumentOutOfRangeException如果範例嘗試在集合完全擴展之前顯示集合中的七個專案,則會擲回。It throws an ArgumentOutOfRangeException if the example attempts to display the seven items in the collection before the collection is fully populated.

    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 Example
    {
       static List<Continent> continents = new List<Continent>();
       static String 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(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();
          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()
    
    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 this case, two resources are accessed from multiple threads:

    • continents 集合。The continents collection. List<T>.Add從多個執行緒呼叫其方法。Its List<T>.Add method is called from multiple threads. 此外,主要或主要執行緒會假設集合在逐一查看其成員時,完全填入了七個元素。In addition, the main or primary thread assumes the collection is fully populated with seven elements when it iterates its members.

    • msg從多個執行緒串連的字串。The msg string, which is concatenated from multiple threads.

    若要更正錯誤,請確定以安全線程的方式存取共用狀態,如下所示。To correct the error, ensure that shared state is accessed in a thread-safe way, as follows.

    • 如果您的應用程式使用陣列或集合物件,請考慮使用安全線程集合類別,例如命名空間中的類型 System.Collections.Concurrent 或頻外 System.Collections.Immutable 發行。if your app uses an array or collection object, consider using a thread-safe collection class, such as the types in the System.Collections.Concurrent namespace or the System.Collections.Immutable out-of-band release.

    • 確定共用狀態 (也就是,可由多個執行緒存取的資源) 會以安全線程的方式存取,因此,一次只能有一個執行緒擁有資源的獨佔存取權。Ensure that shared state (that is, resources that can be accessed by multiple threads) is accessed in a thread-safe way, so that only one thread at a time has exclusive access to the resources. 有大量的類別(例如 CountdownEventInterlockedMonitorMutex )可以用來同步存取資源。A large number of classes, such as CountdownEvent, Interlocked, Monitor, and Mutex, are available to synchronize access to resources. 如需詳細資訊,請參閱 執行緒For more information, see Threading. 此外,語言支援可透過 c # 中的 lock 語句和 Visual Basic 中的 SyncLock 結構取得。In addition, language support is available through the lock statement in C# and the SyncLock construct in Visual Basic.

    下列範例會解決 ArgumentOutOfRangeException 先前範例中的和其他問題。The following example addresses the ArgumentOutOfRangeException and the other issues from the previous example. 它會以 List<T> 物件取代物件 ConcurrentBag<T> ,以確保對集合的存取是安全線程、使用 CountdownEvent 物件來確保應用程式執行緒只會在執行其他執行緒之後繼續執行,並使用鎖定來確保一次只能有一個執行緒存取 msg 變數。It replaces the List<T> object with a ConcurrentBag<T> object to ensure that access to the collection is thread-safe, uses a CountdownEvent object to ensure that the application thread continues only after other threads have executed, and uses a lock to ensure that only one thread can access the msg variable at a time.

    using System;
    using System.Collections.Concurrent;
    using System.Threading;
    
    public class Continent
    {
       public String Name { get; set; }
       public int Population { get; set; }
       public Decimal Area { get; set; }
    }
    
    public class Example
    {
       static ConcurrentBag<Continent> continents = new ConcurrentBag<Continent>();
       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(PopulateContinents);
             th.Start(name);
          }
    
          // Display the list.
          gate.Wait();
          Console.WriteLine(msg);
          Console.WriteLine();
    
          var arr = continents.ToArray();
          for (int ctr = 0; ctr < names.Length; ctr++) {
             var continent = arr[ctr];
             Console.WriteLine("{0}: Area: {1}, Population {2}",
                               continent.Name, continent.Population,
                               continent.Area);
          }
       }
    
       private static void PopulateContinents(Object obj)
       {
          String name = obj.ToString();
          lock(msg) {
             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(25);
          continents.Add(continent);
          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 0
    
    Imports 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 使用 HRESULT COR_E_ARGUMENTOUTOFRANGE,其值為0x80131502。ArgumentOutOfRangeException uses the HRESULT COR_E_ARGUMENTOUTOFRANGE, which has the value 0x80131502.

如需執行個體的初始屬性值的清單ArgumentOutOfRangeException,請參閱ArgumentOutOfRangeException建構函式。For a list of initial property values for an instance of ArgumentOutOfRangeException, see the ArgumentOutOfRangeException constructors.

建構函式

ArgumentOutOfRangeException()

初始化 ArgumentOutOfRangeException 類別的新執行個體。Initializes a new instance of the ArgumentOutOfRangeException class.

ArgumentOutOfRangeException(SerializationInfo, StreamingContext)

使用序列化資料,初始化 ArgumentOutOfRangeException 類別的新執行個體。Initializes a new instance of the ArgumentOutOfRangeException class with serialized data.

ArgumentOutOfRangeException(String)

使用造成這個例外狀況的參數名稱來初始化 ArgumentOutOfRangeException 類別的新執行個體。Initializes a new instance of the ArgumentOutOfRangeException class with the name of the parameter that causes this exception.

ArgumentOutOfRangeException(String, Exception)

使用指定的錯誤訊息和造成這個例外狀況的例外狀況,初始化 ArgumentOutOfRangeException 類別的新執行個體。Initializes a new instance of the ArgumentOutOfRangeException class with a specified error message and the exception that is the cause of this exception.

ArgumentOutOfRangeException(String, Object, String)

使用參數名稱引數值和指定的錯誤訊息,初始化 ArgumentOutOfRangeException 類別的新執行個體。Initializes a new instance of the ArgumentOutOfRangeException class with the parameter name, the value of the argument, and a specified error message.

ArgumentOutOfRangeException(String, String)

使用造成這個例外狀況的參數名稱和指定的錯誤訊息,初始化 ArgumentOutOfRangeException 類別的新執行個體。Initializes a new instance of the ArgumentOutOfRangeException class with the name of the parameter that causes this exception and a specified error message.

屬性

ActualValue

取得造成這個例外狀況的引數值。Gets the argument value that causes this exception.

Data

取得鍵值組的集合,這些鍵值組會提供關於例外狀況的其他使用者定義資訊。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(繼承來源 Exception)
HelpLink

取得或設定與這個例外狀況相關聯的說明檔連結。Gets or sets a link to the help file associated with this exception.

(繼承來源 Exception)
HResult

取得或設定 HRESULT,它是指派給特定例外狀況的編碼數值。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(繼承來源 Exception)
InnerException

取得造成目前例外狀況的 Exception 執行個體。Gets the Exception instance that caused the current exception.

(繼承來源 Exception)
Message

取得錯誤訊息和無效引數值的字串表示,或如果引數值是 null 時,只取得錯誤訊息。Gets the error message and the string representation of the invalid argument value, or only the error message if the argument value is null.

ParamName

取得造成這個例外狀況的參數名稱。Gets the name of the parameter that causes this exception.

(繼承來源 ArgumentException)
Source

取得或設定造成錯誤的應用程式或物件的名稱。Gets or sets the name of the application or the object that causes the error.

(繼承來源 Exception)
StackTrace

取得呼叫堆疊上即時運算框架的字串表示。Gets a string representation of the immediate frames on the call stack.

(繼承來源 Exception)
TargetSite

取得擲回目前例外狀況的方法。Gets the method that throws the current exception.

(繼承來源 Exception)

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetBaseException()

在衍生類別中覆寫時,傳回一或多個後續的例外狀況的根本原因 ExceptionWhen overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(繼承來源 Exception)
GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetObjectData(SerializationInfo, StreamingContext)

以無效的引數值和其他例外狀況資訊設定 SerializationInfo 物件。Sets the SerializationInfo object with the invalid argument value and additional exception information.

GetObjectData(SerializationInfo, StreamingContext)

設定具有參數名稱和額外例外狀況資訊的 SerializationInfo 物件。Sets the SerializationInfo object with the parameter name and additional exception information.

(繼承來源 ArgumentException)
GetType()

取得目前執行個體的執行階段類型。Gets the runtime type of the current instance.

(繼承來源 Exception)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

建立並傳回目前例外狀況的字串表示。Creates and returns a string representation of the current exception.

(繼承來源 Exception)

事件

SerializeObjectState

當例外狀況序列化,以建立包含例外狀況相關序列化資料的例外狀況狀態物件時,就會發生此事件。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(繼承來源 Exception)

適用於

另請參閱