【发布时间】:2014-01-31 09:49:18
【问题描述】:
我在for 循环中创建了一个名为x 的Random 类对象并调用x.next(1,7),它应该返回一个介于1 和6 之间的变量,对象创建和x.next() 函数都已放置在 for 循环中执行 5 次而不是返回随机变量,它在每次迭代中返回相同的值
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
for(int i=1;i<=5;i++)
{
Random x = new Random();
Console.WriteLine( x.Next(1,7));
}
}
}
}
我的输出如下
5
5
5
5
5
当我将对象声明放在循环之外时,它会在每次迭代中返回随机变量
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Random x = new Random();
for(int i=1;i<=5;i++)
{
Console.WriteLine( x.Next(1,7));
}
}
}
}
这次我的输出是
4
5
9
3
1
当x 被声明为类 Program 的静态变量时也可以使用,如下所示
using System;
namespace ConsoleApplication1
{
class Program
{
static Random x = new Random();
static void Main(string[] args)
{
for(int i=1;i<=5;i++)
{
Console.WriteLine( x.Next(1,7));
}
}
}
}
现在输出是
4
7
3
7
9
但我想知道为什么在循环内声明对象时它返回相同的值 当对象变量被声明为静态时会发生什么?
【问题讨论】:
-
我想知道当对象变量(这里是x)被声明为类的静态变量(这里是程序)时会发生什么