System.Random.Next 方法 (Int32, Int32)

方法描述

返回一个指定范围内的随机数。

语法定义(C# System.Random.Next 方法 (Int32, Int32) 的用法)

public virtual int Next(
	int minValue,
	int maxValue
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
minValue System-Int32 返回的随机数的下界(随机数可取该下界值)。
maxValue System-Int32 返回的随机数的上界(随机数不能取该上界值)。maxValue 必须大于或等于 minValue。
返回值 System.Int32 一个大于等于 minValue 且小于 maxValue 的 32 位带符号整数,即:返回的值范围包括 minValue 但不包括 maxValue。 如果 minValue 等于 maxValue,则返回 minValue。

提示和注释

不像 Next 方法的其他重载只返回非负值,该方法可以返回负的随机整数。

对继承者的说明

从 .NET Framework 2.0 版开始,如果您从 Random 派生类并重写 Sample 方法,并且 minValue 与 maxValue 参数的差大于 Int32.MaxValue,则在调用 Random.Next(Int32, Int32) 方法重载的基类实现时将不使用由 Sample 方法的派生类实现提供的分布。 而是使用由 Random 基类返回的统一分布。 此行为提高了 Random 类的总体性能。 若要修改此行为以在派生类中调用 Sample 方法,还必须重写 Random.Next(Int32, Int32) 方法重载。

System.Random.Next 方法 (Int32, Int32)例子

请注意从该示例确切输出取决于传递给 Random 类构造函数的系统提供的种子值。

using System;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();

      Console.WriteLine("\n20 random integers from -100 to 100:");
      for (int ctr = 1; ctr <= 20; ctr++) 
      {
         Console.Write("{0,6}", rnd.Next(-100, 101));
         if (ctr % 5 == 0) Console.WriteLine();
      }

      Console.WriteLine("\n20 random integers from 1000 to 10000:");      
      for (int ctr = 1; ctr <= 20; ctr++) 
      {
         Console.Write("{0,8}", rnd.Next(1000, 10001));
         if (ctr % 5 == 0) Console.WriteLine();
      }

      Console.WriteLine("\n20 random integers from 1 to 10:");
      for (int ctr = 1; ctr <= 20; ctr++) 
      {
         Console.Write("{0,6}", rnd.Next(1, 11));
         if (ctr % 5 == 0) Console.WriteLine();
      }
   }
}
// The example displays output similar to the following:
//       20 random integers from -100 to 100:
//           65   -95   -10    90   -35
//          -83   -16   -15   -19    41
//          -67   -93    40    12    62
//          -80   -95    67   -81   -21
//       
//       20 random integers from 1000 to 10000:
//           4857    9897    4405    6606    1277
//           9238    9113    5151    8710    1187
//           2728    9746    1719    3837    3736
//           8191    6819    4923    2416    3028
//       
//       20 random integers from 1 to 10:
//            9     8     5     9     9
//            9     1     2     3     8
//            1     4     8    10     5
//            9     7     9    10     5

异常

异常 异常描述
ArgumentOutOfRangeException minValue 大于 maxValue。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。