C# CS0120:非静态字段、方法或属性“foo”需要对象引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/498400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:44:10  来源:igfitidea点击:

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

c#

提问by huda

Consider:

考虑:

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

Why is this error occurring?

为什么会发生此错误?

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

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

采纳答案by huda

It looks like you are calling a non static member (a property or method, specifically setTextboxText) from a static method (specifically SumData). You will need to either:

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

  1. Make the called member static also:

    static void setTextboxText(int result)
    {
        // Write static logic for setTextboxText.  
        // This may require a static singleton instance of Form1.
    }
    
  2. Create an instance of Form1within the calling method:

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

    Passing in an instance of Form1would be an option also.

  3. Make the calling method a non-static instance method (of 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);
    }
    
  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. 使调用方法成为非静态实例方法(of 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);
    }
    

More info about this error can be found on MSDN.

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

回答by Brian Rasmussen

You start a thread which runs the static method SumData. However, SumDatacalls SetTextboxTextwhich isn't static. Thus you need an instance of your form to call SetTextboxText.

您启动一个运行静态方法的线程SumData。但是,SumData调用SetTextboxText不是静态的。因此,您需要一个表单实例来调用SetTextboxText.

回答by Abd Al-Kareem Attiya

From my looking you give a null value to a textbox and return in a ToString()as it is a static method. You can replace it with Convert.ToString()that can enable null value.

从我的角度来看,您为文本框提供了一个空值并在 a 中返回,ToString()因为它是一个静态方法。您可以将其替换为 Convert.ToString()可以启用空值。

回答by issam chouchane

Your method must be static

你的方法必须是静态的

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

回答by COOLGAMETUBE

For this case, where you want to get a Control of a Form and are receiving this error, then I have a little bypass for you.

对于这种情况,您想要获得表单控件并收到此错误,那么我为您提供了一些绕过。

Go to your Program.cs and change

转到您的 Program.cs 并更改

Application.Run(new Form1());

to

public static Form1 form1 = new Form1(); // Place this var out of the constructor
Application.Run(form1);

Now you can access a control with

现在你可以访问一个控件

Program.form1.<Your control>

Also: Don't forget to set your Control-Access-Level to Public.

另外:不要忘记将您的控制访问级别设置为公共。

And yes I know, this answer does not fit to the question caller, but it fits to googlers who have this specific issue with controls.

是的,我知道,这个答案不适合提问者,但适合有这个特定控件问题的谷歌员工。

回答by veggiebenz

Credit to @COOLGAMETUBE for tipping me off to what ended up working for me. His idea was good but I had a problem when Application.SetCompatibleTextRenderingDefault was called after the form was already created. So with a little change, this is working for me:

感谢@COOLGAMETUBE 向我透露了最终对我有用的东西。他的想法很好,但我在创建表单后调用 Application.SetCompatibleTextRenderingDefault 时遇到了问题。所以稍作改动,这对我有用:


static class Program
{
    public static Form1 form1; // = new Form1(); // Place this var out of the constructor

/// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(form1 = new Form1()); } }

回答by Max Alexander Hanna

I actually got this error because I was checking InnerHtml for some content that was generated dynamically - i.e. a control that is runat=server.

我实际上收到了这个错误,因为我正在检查 InnerHtml 中是否有一些动态生成的内容 - 即 runat=server 的控件。

To solve this I had to remove the "static" keyword on my method, and it ran fine.

为了解决这个问题,我必须在我的方法中删除“static”关键字,并且它运行良好。