【问题标题】:CS0120: An object reference is required for the nonstatic field, method, or property 'foo'CS0120:非静态字段、方法或属性“foo”需要对象引用
【发布时间】:2009-01-31 06:22:02
【问题描述】:

考虑:

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)”需要对象引用

【问题讨论】:

    标签: c#


    【解决方案1】:

    看起来您正在从静态方法(特别是 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找到。

    【讨论】:

      【解决方案2】:

      对于这种情况,如果您想要获取表单的控件并收到此错误,那么我可以为您提供一点绕过。

      转到您的 Program.cs 并进行更改

      Application.Run(new Form1());
      

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

      现在您可以使用

      访问控件了
      Program.form1.<Your control>
      

      另外:不要忘记将您的 Control-Access-Level 设置为 Public。

      是的,我知道,这个答案不适合提问者,但它适合在控件方面有这个特定问题的谷歌人。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 这个答案似乎重申了这个问题。它没有解释为什么会产生错误。
        • @Robert 所有其他答案都没有......这个评论毫无意义
        【解决方案4】:

        你的方法必须是静态的

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

        【讨论】:

        • 此特定方法显式访问实例属性(特别是this.InvokeRequiredthis.Invoke),因此不能设为静态。
        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

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

          为了解决这个问题,我不得不删除我的方法中的“静态”关键字,它运行良好。

          【讨论】:

            【解决方案7】:

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

            【讨论】:

              【解决方案8】:

              使函数静态化。这一定能解决你的问题。

              【讨论】:

                【解决方案9】:

                您的问题的本质和解决方案是:

                using System;
                
                namespace myNameSpace
                {
                    class Program
                    {
                        private void method()
                        {
                            Console.WriteLine("Hello World!");
                        }
                
                        static void Main(string[] args)
                        {
                            method();//<-- Compile Time error because an instantiation of the Program class doesnt exist
                            Program p = new Program();
                            p.method();//Now it works. (You could also make method() static to get it to work)
                        }
                    }
                }
                

                【讨论】:

                  猜你喜欢
                  • 2019-06-22
                  • 2016-05-13
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多