首頁 >後端開發 >C++ >為什麼從靜態方法調用非靜態方法會導致'需要對象引用”?

為什麼從靜態方法調用非靜態方法會導致'需要對象引用”?

Susan Sarandon
Susan Sarandon原創
2025-02-02 17:41:11284瀏覽

Why Does Calling a Non-Static Method from a Static Method Cause

c#錯誤cs0120:必需對象參考

>

此錯誤,“非靜態字段,方法或屬性……需要從靜態方法中訪問非靜態成員(例如setTextboxText)時,就會出現對象引用... >)。 讓我們檢查提供的代碼:SumData

<code class="language-csharp">namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        // ... other code ...

        private static void SumData(object state)
        {
            // ... some code to calculate 'result' ...
            setTextboxText(result); // Error occurs here
        }

        // ... other code ... including setTextboxText method ...
    }
}</code>
問題在於靜態成員和非靜態成員之間的基本差異:>

    >靜態成員:屬於
  • class 本身,而不是類的任何特定實例。 它們甚至在創建班級的任何對象之前就存在。 > 非靜態成員:屬於類的
  • 實例
  • 。 您需要一個對象(實例)才能訪問它們。 > >由於是靜態的,因此它沒有關聯的
  • 對象。 因此,它不能直接調用
,它需要一個對象才能操作。

> SumDataForm1>解決方案: setTextboxText

有兩種修復此問題的主要方法:

1。製作

靜態:

>如果>本質上不需要訪問特定於實例的數據或setTextboxText>的成員,則可以使其靜態:

>setTextboxText>謹慎:Form1使與UI相關的方法靜態通常不含糊不清,因為它可能導致線程問題並使代碼更難維護。 >

<code class="language-csharp">public static void setTextboxText(int result)
{
    // Code to update the textbox.  This might require accessing the textbox 
    // statically (e.g., if it's a public static member of Form1).  This is often 
    // not ideal for UI elements.
}</code>
2。從非靜態方法調用

(推薦):>

這是更清潔,更常見的解決方案。 您需要一種非靜態方法來充當中介:

setTextboxText>如何訪問

>

>的實例(對於選項2):

<code class="language-csharp">private void UpdateTextbox(int result)
{
    setTextboxText(result); // This is now safe
}

private static void SumData(object state)
{
    // ... calculate 'result' ...
    // Access the Form1 instance using a delegate or other mechanism
    // (see examples below)
    this.BeginInvoke(new Action(() => UpdateTextbox(result))); //Example using BeginInvoke for UI thread safety
}</code>
>

最佳方法取決於如何調用。 以下是一些常見的情況:Form1 SumData

> ifSumData>在

>的方法中調用:
    >您可以直接使用
  • >(如上示例所示)。

    SumData>Form1如果是從背景線程或計時器調用>:您需要使用委託將調用返回給UI線程以避免交叉線程異常:this>

<code class="language-csharp">namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        // ... other code ...

        private static void SumData(object state)
        {
            // ... some code to calculate 'result' ...
            setTextboxText(result); // Error occurs here
        }

        // ... other code ... including setTextboxText method ...
    }
}</code>
  • >如果是從一個完全獨立的類調用SumData>:您需要一種將對>實例的引用的引用到。 這可能涉及將其作為參數將其傳遞給Form1或將其引用在靜態字段中(儘管由於潛在的並發症,這通常不太優先)。 SumData SumData記住選擇最適合應用程序上下文的解決方案,並在處理UI元素時始終優先考慮線程安全性。 選項2,使用非靜態中介方法和適當的螺紋,通常是最健壯和可維護的解決方案。

以上是為什麼從靜態方法調用非靜態方法會導致'需要對象引用”?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn