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

前端 未结 7 1276
挽巷
挽巷 2020-11-21 04:34

Consider:

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


        
7条回答
  •  长情又很酷
    2020-11-21 05:13

    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:

    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 Form1 within 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 Form1 would 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);
      }
      

    More info about this error can be found on MSDN.

提交回复
热议问题