Error and solution for C# Static method cannot access non-static members
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:
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.
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;.
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.
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.
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