C# static method cannot access the errors and solutions of non -static members
Error: The object is referenced
The following code fragment demonstrates this problem:
The cause of the problem
<code class="language-csharp">namespace WindowsApplication1 { public partial class Form1 : Form { ... private static void SumData(object state) { ... setTextboxText(result); // 错误:非静态字段、方法或属性 } } }</code>
Error information shows that static methods try to call non -static members
. Static methods can only access static members, and non -static members need a reference to objects that belong to.
SumData
Solution setTextboxText
There are many ways to solve this error:
Set themethod as static:
setTextboxText
However, if the method needs to access instance variables, it cannot be set to static.
<code class="language-csharp">public static void setTextboxText(int result)</code>
setTextboxText
Form1
. setTextboxText
<code class="language-csharp">class Form1 { public static Form1 Instance; // 单例 ... private static void SumData(object state) { ... Instance.setTextboxText(result); } }</code>
Form1
Instance
Instance = this;
If the instance already exists, this method may not be applicable.
Form1
): <code class="language-csharp">private static void SumData(object state) { ... Form1 frm1 = new Form1(); frm1.setTextboxText(result); }</code>
This is usually the best solution because it maintains the encapsulation and maintenance of the code. Form1
The above is the detailed content of Why Can't a Static Method Access Non-Static Members in C#?. For more information, please follow other related articles on the PHP Chinese website!