0

我收到一条错误消息“非静态字段、方法或属性需要对象引用......”以调用 Refresh 函数:

// 地位

    public static string Status 
    {
        get 
          { 
              return status; 
          }
        set 
        {
            status = value;
            Refresh();
        } 
    }

    private void Refresh()
    {
        lblStatus.Text = Status.ToString();
    }
4

4 回答 4

2

您只能从静态函数调用静态函数。

它应该像

public static string Status 
{
    get 
    { 
       return status; 
    }
    set 
    {
        status = value;
        Refresh();
    } 
}

private static void Refresh()  // Change signature of function
{
    lblStatus.Text = Status.ToString();
}

或者

使属性非静态

public string Status // Change signature of property 
{
    get 
    { 
       return status; 
    }
    set 
    {
        status = value;
        Refresh();
    } 
}

private void Refresh()
{
    lblStatus.Text = Status.ToString();
}
于 2012-05-18T08:36:26.437 回答
2

只需将Status属性设为非静态。显然,您不会在该类的所有实例中共享此属性。看起来您正在使用控件或页面类,并且还尝试调用其他实例方法或属性。

所以这将修复编译错误。

public string Status 
....
于 2012-05-18T08:41:24.080 回答
0

我认为这是一个糟糕的设计,因为 lblStatus 是一个控件,我猜,所以它不能是静态的,所以 Refresh 不能是静态的。

因此,无论如何,您都不应该在静态上下文中调用 Refresh() ......

于 2012-05-18T08:42:47.767 回答
0

这是一个糟糕的设计。您应该从状态中删除静态。

您要做的是从静态属性设置实例值。

您只能从静态属性/方法修改静态字段/属性。

如果您坚持 Status 必须是 Static,那么您必须创建另一个静态属性/字段并通过该字段进行更新。(这非常糟糕)。

示例:假设在 Form1 类中定义了 Status,那么 Form1 的实例就只有一个

    Class Form1
    {
        private static Form1 staticInstance = default(Form1);
        Form1()
            {
            staticInstance  = this;
            }
        public static string Status 
        {
            get 
            { 
            return status; 
            }
            set 
            {
                status = value;
                Refresh();
            } 
        }

        private static void Refresh()  // Change signature of function
        {
            if(staticInstance  != default(Form1)
            staticInstance .lblStatus.Text = Status.ToString();
        }

    }
于 2012-05-18T09:59:18.690 回答