日期:2014-05-18  浏览次数:20838 次

Random问题
namespace WindowsApplication2
{
  public partial class Form1 : Form
  {  
  Random aa = new Random();
  Random bb = new Random();
int cc = aa.Next(0, 100);
int dd = bb.Next(0, 100); private void button2_Click(object sender, EventArgs e)
  {
  //int cc = aa.Next(0, 100);
  //int dd = bb.Next(0, 100);
  textBox1.Text = Convert.ToString(cc);
  textBox2.Text = Convert.ToString(dd);
   
  }


  ....


  }
}
标红的的提示错误:
字段初始值设定项无法引用非静态字段、方法或属性。
“WindowsApplication2.Form1.aa”

为什么呢??
好像在
 private void button2_Click(object sender, EventArgs e)
  {
  Random aa = new Random();
  Random bb = new Random();
  int cc = aa.Next(0, 100);
  int dd = bb.Next(0, 100);
  textBox1.Text = Convert.ToString(cc);
  textBox2.Text = Convert.ToString(dd);
   
  }
就没有问题!!
怎会是呢?谢谢

------解决方案--------------------
namespace WindowsApplication2 

public partial class Form1 : Form 
{
static Random aa = new Random();
static Random bb = new Random(); int cc = aa.Next(0, 100); 
int dd = bb.Next(0, 100); private void button2_Click(object sender, EventArgs e) 

//int cc = aa.Next(0, 100); 
//int dd = bb.Next(0, 100); 
textBox1.Text = Convert.ToString(cc); 
textBox2.Text = Convert.ToString(dd); 




.... 





------解决方案--------------------
加静态
------解决方案--------------------

private static Random rand = new Random(); 
int cc = aa.Next(0, 100); 
...
具体查看
http://msdn.microsoft.com/zh-cn/library/2dx6wyd4.aspx
------解决方案--------------------
声明和方法里面不一样
------解决方案--------------------
因为它算是局部变量

------解决方案--------------------
探讨
哦,谢谢!
不过:

private void button2_Click(object sender, EventArgs e)
{
Random aa = new Random();
Random bb = new Random();
int cc = aa.Next(0, 100);
int dd = bb.Next(0, 100);
textBox1.Text = Convert.ToString(cc);
textBox2.Text = Convert.ToString(dd);

}
为啥是对的呢??

------解决方案--------------------
类成员的'静态'初始化不能依赖以其他类成员(存在编译优化,int j可能排在int i前面。如果存在依赖,会有其他类成员可能还没有初始化的问题)。
所以下面例子一个是错误的,一个是正确的:

C# code

class A
{
  int i = 1;
  int j = i + 1;        //<---错误
}

class A
{
  int i;
  int j; 

  public A()
  {
     i = 1;            //执行顺序是确定的
     j = i + 1;        //ok
  }
}