首页 文章

获取/设置错误“非静态字段需要对象引用...”

提问于
浏览
0

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

//状态公共静态字符串状态
{
得到
{
返回状态;
}

{
status = value;
刷新();
}
}

private void Refresh()

4 回答

  • 2

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

    所以这将解决编译错误 .

    public string Status 
    ....
    
  • 0

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

    应该是这样的

    public static string Status 
    {
        get 
        { 
           return status; 
        }
        set 
        {
            status = value;
            Refresh();
        } 
    }
    
    private static void Refresh()  // Change signature of function
    {
        lblStatus.Text = Status.ToString();
    }
    

    OR

    使属性非静态

    public string Status // Change signature of property 
    {
        get 
        { 
           return status; 
        }
        set 
        {
            status = value;
            Refresh();
        } 
    }
    
    private void Refresh()
    {
        lblStatus.Text = Status.ToString();
    }
    
  • 0

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

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

  • 2

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

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

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

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

    示例:假设Status在Form1类中定义,并且只有一个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();
            }
    
        }
    

相关问题