>
方案:
想像此代碼:
<code class="language-csharp">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) } }</code>
>解決方案:
>。 僅當成員不依賴特定於實例的數據時才能起作用。
static
<code class="language-csharp">public static void UpdateLabel(string text) // Now static { // Access static members only here! You can't access myLabel directly. }</code>>
>
在靜態方法中創建類的實例<code class="language-csharp">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 }</code>
>
使調用方法非靜態:private static void MyMethod(object sender, EventArgs e)
{
var form = new MyForm();
form.UpdateLabel(someValue);
}
進一步讀取:
<code class="language-csharp">private void MyMethod(object sender, EventArgs e) // Remains non-static { UpdateLabel(someValue); }</code>>有關CS0120錯誤的Microsoft文檔以獲取更多詳細信息。
以上是如何解決C#CS0120錯誤:'非靜態字段,方法或屬性需要對象引用”?的詳細內容。更多資訊請關注PHP中文網其他相關文章!