小编典典

CS0120:非静态字段,方法或属性'foo'需要对象引用

c#

考虑:

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //int[] val = { 0, 0};
            int val;
            if (textBox1.Text == "")
            {
                MessageBox.Show("Input any no");
            }
            else
            {
                val = Convert.ToInt32(textBox1.Text);
                Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));
                ot1.Start(val);
            }
        }

        private static void ReadData(object state)
        {
            System.Windows.Forms.Application.Run();
        }

        void setTextboxText(int result)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });
            }
            else
            {
                SetTextboxTextSafe(result);
            }
        }

        void SetTextboxTextSafe(int result)
        {
            label1.Text = result.ToString();
        }

        private static void SumData(object state)
        {
            int result;
            //int[] icount = (int[])state;
            int icount = (int)state;

            for (int i = icount; i > 0; i--)
            {
                result += i;
                System.Threading.Thread.Sleep(1000);
            }
            setTextboxText(result);
        }

        delegate void IntDelegate(int result);

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

为什么会发生此错误?

非静态字段,方法或属性’WindowsApplication1.Form1.setTextboxText(int)需要对象引用


阅读 439

收藏
2020-05-19

共1个答案

小编典典

看起来您正在setTextboxText从静态方法(特别是SumData)调用非静态成员(特别是属性或方法)。您将需要:

  1. 也将被叫成员设为静态:

    static void setTextboxText(int result)
    

    {
    // Write static logic for setTextboxText.
    // This may require a static singleton instance of Form1.
    }

  2. Form1在调用方法中创建一个实例:

    private static void SumData(object state)
    

    {
    int result = 0;
    //int[] icount = (int[])state;
    int icount = (int)state;

    for (int i = icount; i > 0; i--)
    {
        result += i;
        System.Threading.Thread.Sleep(1000);
    }
    Form1 frm1 = new Form1();
    frm1.setTextboxText(result);
    

    }

Form1也可以选择传入的实例。

  1. 将调用方法设为(Form1)的非静态实例方法:
    private void SumData(object state)
    

    {
    int result = 0;
    //int[] icount = (int[])state;
    int icount = (int)state;

    for (int i = icount; i > 0; i--)
    {
        result += i;
        System.Threading.Thread.Sleep(1000);
    }
    setTextboxText(result);
    

    }

可以在MSDN上找到有关此错误的更多信息。

2020-05-19