>
方案:
想象此代码:
public partial class MyForm : Form { private void MyMethod(object sender, EventArgs e) { // Error: Accessing a non-static member from a static method UpdateLabel(someValue); } private void UpdateLabel(string text) { myLabel.Text = text; // myLabel is a non-static member (control) } }
>解决方案:
>。 仅当成员不依赖特定于实例的数据时才能起作用。
static
public static void UpdateLabel(string text) // Now static { // Access static members only here! You can't access myLabel directly. }
>
在静态方法中创建类的实例public partial class MyForm : Form { private static MyForm _instance; // Singleton instance public static MyForm Instance { get { return _instance ?? (_instance = new MyForm()); } } private MyForm() { } // Private constructor private void MyMethod(object sender, EventArgs e) { Instance.UpdateLabel(someValue); } // UpdateLabel remains non-static }
>
使调用方法非静态:private static void MyMethod(object sender, EventArgs e) { var form = new MyForm(); form.UpdateLabel(someValue); }
进一步读取:
private void MyMethod(object sender, EventArgs e) // Remains non-static { UpdateLabel(someValue); }
以上是如何解决C#CS0120错误:'非静态字段,方法或属性需要对象引用”?的详细内容。更多信息请关注PHP中文网其他相关文章!