2

这是我的代码的样子:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FJBch09ex10
{


    public partial class Form1 : Form
    {
        Random r = new Random();
        int num = r.Next(0, 100);
        int counter = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btn1_Click(object sender, EventArgs e)
        {
            counter++;

            if (int.Parse(txt1.Text) > num)
            {
                lbl1.Text = "the number is too high";
                Form1.BackColor = HotTrack;


            }
            else {
                lbl1.Text = "the number is too low";
                Form1.BackColor = MenuHighlight;
            }

        }


    }
}

目前 r.Next 中的 r 正在运行错误。Form1.BackColor 尝试也都是运行错误。知道为什么这些是运行错误吗?r 表示“字段初始值设定项无法引用非静态字段......”Form1 表示“非静态字段需要对象引用......”

4

3 回答 3

2
public partial class Form1 : Form
{
    Random r = new Random();
    int num; // you cannot use r there
    int counter = 0;

    public Form1()
    {
        InitializeComponent();
        num = r.Next(0, 100); // you can use r there
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void btn1_Click(object sender, EventArgs e)
    {
        counter++;

        if (int.Parse(txt1.Text) > num)
        {
            lbl1.Text = "the number is too high";
            BackColor = SystemColors.HotTrack; // Form1 is the class


        }
        else {
            lbl1.Text = "the number is too low";
            BackColor = SystemColors.MenuHighlight; // Form1 is the class
        }

    }
}
于 2013-09-10T18:29:16.867 回答
1
  1. 您不能假设字段按照声明的顺序进行初始化。所以你应该把num初始化移到构造函数中,或者标记r为静态的。

    Random r = new Random();
    int num;
    int counter = 0;
    
    public Form1()
    {
        InitializeComponent();
        num = r.Next();
    }
    
  2. BackColor不是Form1类的静态属性。它是一个实例属性,因此您必须使用this关键字或只设置没有任何标识符的属性:

    this.BackColor = MenuHighlight;
    

    或者

    BackColor = MenuHighlight;
    
于 2013-09-10T18:30:40.487 回答
0

你需要改变

Form1.BackColor = ...;

this.BackColor = ...;

因为您希望引用当前对象属性,而不是对象的静态属性。

并且您需要在表单构造函数中设置 num 的值。

就像是

public partial class Form1 : Form
{
    Random r = new Random();
    int num ;
    int counter = 0;

    public Form1()
    {
        InitializeComponent();
        num = r.Next(0, 100);

    }
    ....
于 2013-09-10T18:27:50.780 回答