首頁 > 後端開發 > C++ > 如何解決C#CS0120錯誤:'非靜態字段,方法或屬性需要對象引用”?

如何解決C#CS0120錯誤:'非靜態字段,方法或屬性需要對象引用”?

Linda Hamilton
發布: 2025-02-02 17:56:09
原創
482 人瀏覽過

How to Resolve the C# CS0120 Error:

> c#c​​s0120錯誤:“非靜態字段,方法或屬性'foo'”

需要對象引用 當您嘗試從靜態上下文(例如靜態方法或靜態屬性)中訪問非靜態成員(字段,方法或屬性)時,此錯誤就會出現。

>

方案:

想像此代碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

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)

    }

}

登入後複製

>解決方案: 幾種方法可以解決以下方法:

    >
  1. 使成員靜態:如果適當,將訪問的成員更改為

    >。 僅當成員不依賴特定於實例的數據時才能起作用。 static

    1

    2

    3

    4

    public static void UpdateLabel(string text) // Now static

    {

        // Access static members only here!  You can't access myLabel directly.

    }

    登入後複製
    >
  2. >單例模式:
  3. 使用單例訪問類的實例。 當您僅需要一個類實例時,這是合適的。

    >

    在靜態方法中創建類的實例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    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

    }

    登入後複製
  4. >
  5. >

    使調用方法非靜態:

    1

    2

    3

    4

    5

    private static void MyMethod(object sender, EventArgs e)

    {

        var form = new MyForm();

        form.UpdateLabel(someValue);

    }

    登入後複製
  • 進一步讀取:

    1

    2

    3

    4

    private void MyMethod(object sender, EventArgs e) // Remains non-static

    {

        UpdateLabel(someValue);

    }

    登入後複製
    >有關CS0120錯誤的Microsoft文檔以獲取更多詳細信息。 仔細考慮每個解決方案的含義。 選擇正確的方法取決於您的應用程序的設計和代碼的特定上下文。 >

    以上是如何解決C#CS0120錯誤:'非靜態字段,方法或屬性需要對象引用”?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

  • 本網站聲明
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
    作者最新文章
    熱門推薦
    熱門教學
    更多>
    最新下載
    更多>
    網站特效
    網站源碼
    網站素材
    前端模板