无法在静态上下文中访问非静态字段 'lblSystemStatus'

Cannot access non-static field 'lblSystemStatus' in static context

我看过很多关于这个问题的帖子,none 其中有帮助。 我有以下简单的代码:

private delegate void UpdateLabelCallback(Label lbLabel, string val);

防止非法跨线程调用的简单委托。

private static readonly System.Threading.Timer TimerHalfASecond = new System.Threading.Timer(HalfASecondCallback, null,
        500, Timeout.Infinite);

线程计时器

private static void HalfASecondCallback(object state)
{
    UpdateLabel(lblSystemStatus, Resources.DesktopClock_timerOneSecond_Tick_CPU__ + _cpu.GetCpuCounter().ToString() + @"%");
    TimerHalfASecond.Change(500, Timeout.Infinite);
}

静态Threading.Timer回调。 lblSystemStatus 错误显示

"cannot access non-static field 'lblSystemStatus' in static context"

private static void UpdateLabel(Label lbLabel, string val)
{
    if (lbLabel.InvokeRequired)
    {
        var d = new UpdateLabelCallback(UpdateLabel);
        lbLabel.Invoke(d, lbLabel, val);
    }
    else
    {

        lbLabel.Text = val;
    }
}

静态 UpdateLabel 方法。

所以问题是: 当控件上的标签不是静态的并且回调要求它们是静态的时,如何更新控件上的标签?

您将计时器声明为 private static readonly。如果计时器在 class(控件)的实例中运行,我不会这样做。如果你没有做到 static,其他方法就不必这样做,你可以安全地使用实例变量(如果你有两个 class 实例,计时器可能会发生冲突)。

另一种方法是向 Timer 构造函数提供 state 以包含标签,或提供 Func<Label 以检索标签。对于第一个选项,这意味着您必须延迟创建计时器,直到创建标签。

样本:

new System.Threading.Timer(HalfASecondCallback, this.lblStatusText,
    500, Timeout.Infinite);

那么您的处理程序可能是:

private static void HalfASecondCallback(object state)
{
    Label l = state as Label; // in fact lblSystemStatus

    if (l != null)
    {
        UpdateLabel(l, Resources.DesktopClock_timerOneSecond_Tick_CPU__ + _cpu.GetCpuCounter().ToString() + @"%");
        TimerHalfASecond.Change(500, Timeout.Infinite);
    }
}

您可以创建一些静态字段,将您的标签分配给该字段并在静态上下文中使用它