"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Can't a Static Method Access Non-Static Members in C#?

Why Can't a Static Method Access Non-Static Members in C#?

Posted on 2025-03-24
Browse:730

Error and solution for C# Static method cannot access non-static members

Why Can't a Static Method Access Non-Static Members in C#?

Error: Object reference required

]

The following code snippet demonstrates this problem:

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        ...

        private static void SumData(object state)
        {
            ...
            setTextboxText(result); // 错误:非静态字段、方法或属性
        }
    }
}

Cause of the problem

]

Error message indicates that the static method SumData attempts to call a non-static member setTextboxText. A static method can only access static members, while accessing non-static members requires a reference to the object of the class to which it belongs.

Solutions

There are several ways to fix this error:

  1. Set the setTextboxText method to static:
public static void setTextboxText(int result)
]

However, if the setTextboxText method requires access to the instance variable, it cannot be set to static.

  1. static singleton call setTextboxText:]
class Form1
{
    public static Form1 Instance;   // 单例

    ...

    private static void SumData(object state)
    {
        ...
        Instance.setTextboxText(result);
    }
}
In the constructor of

Form1, Instance needs to be set to the current instance: Instance = this;.

  1. Create a Form1 In the calling method:
private static void SumData(object state)
{
    ...
    Form1 frm1 = new Form1();
    frm1.setTextboxText(result);
}
If the instance of

Form1 already exists, this method may not work.

  1. SumDataSet the call method SumData as a non-static instance method (belongs to Form1):
private void SumData(object state)
{
    ...
    setTextboxText(result);
}

This is usually the best solution because it keeps the code encapsulation and maintainability.

For more information, please refer to the MSDN documentation.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3