gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:48 25 4
gpt4 key购买 nike

我已经尝试修复此问题很长时间了,但我不知道它是我的代码还是在 VS 中找不到它。我真的已经尝试了一切,我需要帮助

我得到的错误:

An object reference is required for the non-static field, method, or property 'WindowsFormsApplication3.Form1.label1' c:\users\zmatar\documents\visual studio 2013\projects\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)
{

}
}
}

最佳答案

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

关于c# - 非静态字段、方法或属性需要对象引用 Label1 颜色更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25798603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com