gpt4 book ai didi

c# - CS0120 : An object reference is required for the nonstatic field, 方法或属性 'foo'

转载 作者:IT王子 更新时间:2023-10-29 03:29:17 26 4
gpt4 key购买 nike

考虑:

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();
}
}
}

为什么会出现这个错误?

An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Form1.setTextboxText(int)

最佳答案

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

  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 的实例也是一种选择。

  3. 使调用方法成为非静态实例方法(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);
    }

可以找到有关此错误的更多信息 on MSDN .

关于c# - CS0120 : An object reference is required for the nonstatic field, 方法或属性 'foo',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/498400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com