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
[解决办法]
声明和方法里面不一样
[解决办法]
因为它算是局部变量
[解决办法]
class A{ int i = 1; int j = i + 1; //<---错误}class A{ int i; int j; public A() { i = 1; //执行顺序是确定的 j = i + 1; //ok }}