非静态字段,方法或属性Label1颜色更改需要对象引用

时间:2014-09-11 23:44:12

标签: c#

我一直试图解决这个问题很长一段时间,我不知道它是我的代码还是它无法在VS中找到它。我真的尝试了一切,我需要帮助

我得到错误:

  

非静态字段需要对象引用,   方法或财产   ' WindowsFormsApplication3.Form1.label1' C:\用户\ zmatar \文档\ Visual   工作室   2013 \项目\ windowsformsapplication3 \ windowsformsapplication3 \ Form1.cs中

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.NetworkInformation;

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

        public static void PingTest()
        {
            const int timeout = 120;
            const string data = "[012345678901234567890123456789]";
            var buffer = Encoding.ASCII.GetBytes(data);
            PingReply reply;
            var success = true;    // Start out optimistic!
            var sender = new Ping();

            // Add as many hosts as you want to ping to this list
            var hosts = new List<string> { "www.google.com", "www.432446236236.com" };

            // Ping each host and set the success to false if any fail or there's an exception
            foreach (var host in hosts)
            {
                try
                {
                    reply = sender.Send(host, timeout, buffer);

                    if (reply == null || reply.Status != IPStatus.Success)
                    {
                        // We failed on this attempt - no need to try any others
                        success = false;
                        break;
                    }
                }
                catch
                {
                    success = false;
                }
            }

            if (success)
            {
                label1.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                label1.ForeColor = System.Drawing.Color.Red;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            PingTest();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }
    }
}

1 个答案:

答案 0 :(得分:1)

label1实例变量。您正尝试使用static方法进行设置。

static方法无法访问实例成员而无需转到实例。要解决此问题,请从方法中删除static,或者存储该类的实例以供日后使用:

public class Form1 : Form
{
   static Form1 instance = null;

   public Form1()
   {
       InitializeComponent();
       instance = this;
   }

   private static void MyMethod()
   {
      if (instance != null)
         instance.label1.Color = Color.White; //Or whatever
   }
}