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

C# 非静态字段、方法或属性Label1颜色更改需要对象引用,c#,C#,我已经尝试了很长一段时间来解决这个问题,我不知道这是我的代码还是在VS中找不到。我已经尝试了所有方法,我需要帮助 我得到的错误是: 非静态字段需要对象引用, 方法或属性 “WindowsFormsApplication3.Form1.label1”c:\users\zmatar\documents\visual 演播室 2013\projects\windowsformsapplication3\windowsformsapplication3\form1.cs 代码: 使用系统; 使用Syst

我已经尝试了很长一段时间来解决这个问题,我不知道这是我的代码还是在VS中找不到。我已经尝试了所有方法,我需要帮助

我得到的错误是:

非静态字段需要对象引用, 方法或属性 “WindowsFormsApplication3.Form1.label1”c:\users\zmatar\documents\visual 演播室 2013\projects\windowsformsapplication3\windowsformsapplication3\form1.cs

代码:

使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
使用System.Net.NetworkInformation;
命名空间Windows窗体应用程序3
{
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
}
公共静态无效测试()
{
const int timeout=120;
常量字符串数据=“[0123456789012345678901234567890123456789]”;
var buffer=Encoding.ASCII.GetBytes(数据);
平复复复;
var success=true;//乐观地开始吧!
var sender=new Ping();
//在此列表中添加您想要ping的主机数
var hosts=新列表{“www.google.com”,“www.432446236.com”};
//Ping每个主机,如果有失败或出现异常,则将success设置为false
foreach(主机中的var主机)
{
尝试
{
reply=sender.Send(主机、超时、缓冲区);
if(reply==null | | reply.Status!=IPStatus.Success)
{
//我们这次尝试失败了,没有必要再尝试其他的
成功=错误;
打破
}
}
抓住
{
成功=错误;
}
}
如果(成功)
{
label1.ForeColor=System.Drawing.Color.Red;
}
其他的
{
label1.ForeColor=System.Drawing.Color.Red;
}
}
私有void Form1\u加载(对象发送方、事件参数e)
{
timer1.Start();
}
私有无效计时器1_刻度(对象发送方,事件参数e)
{
PingTest();
}
private void exitToolStripMenuItem\u单击(对象发送者,事件参数e)
{
Close();
}
私有无效菜单已单击IP1\u项(对象发送者、工具条目的ClickedEventArgs e)
{
}
}
}

label1
是一个实例变量。您正试图在
静态方法中设置它

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

@这将产生一个稍微不同的错误。“需要对象引用”错误(几乎?)总是与访问实例内容的
静态
内容有关。可能重复
静态表单1实例=null?@Igor是的,谢谢你的关注。我已编辑以修复。
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
   }
}