首页 >后端开发 >C++ >为什么从静态方法调用非静态方法会导致'需要对象引用”?

为什么从静态方法调用非静态方法会导致'需要对象引用”?

Susan Sarandon
Susan Sarandon原创
2025-02-02 17:41:11337浏览

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