Home > Backend Development > C++ > Why Can't a Static Method Access Non-Static Members in C#?

Why Can't a Static Method Access Non-Static Members in C#?

Susan Sarandon
Release: 2025-02-02 17:46:09
Original
246 people have browsed it

C# static method cannot access the errors and solutions of non -static members

Why Can't a Static Method Access Non-Static Members in C#?

Error: The object is referenced

The following code fragment demonstrates this problem:

The cause of the problem
<code class="language-csharp">namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        ...

        private static void SumData(object state)
        {
            ...
            setTextboxText(result); // 错误:非静态字段、方法或属性
        }
    }
}</code>
Copy after login

Error information shows that static methods try to call non -static members

. Static methods can only access static members, and non -static members need a reference to objects that belong to.

SumData Solution setTextboxText

There are many ways to solve this error:

Set the

method as static:

  1. setTextboxText However, if the method needs to access instance variables, it cannot be set to static.
Call
<code class="language-csharp">public static void setTextboxText(int result)</code>
Copy after login
:

setTextboxText

  1. In the constructor, set to the current instance: Form1. setTextboxText
  2. Create a
instance in the call method:
<code class="language-csharp">class Form1
{
    public static Form1 Instance;   // 单例

    ...

    private static void SumData(object state)
    {
        ...
        Instance.setTextboxText(result);
    }
}</code>
Copy after login

Form1 Instance Instance = this; If the instance already exists, this method may not be applicable.

  1. The call method is set to non -static instance method (belongs to Form1):
<code class="language-csharp">private static void SumData(object state)
{
    ...
    Form1 frm1 = new Form1();
    frm1.setTextboxText(result);
}</code>
Copy after login

This is usually the best solution because it maintains the encapsulation and maintenance of the code. Form1

For more information, please refer to the MSDN document.

    The above is the detailed content of Why Can't a Static Method Access Non-Static Members in C#?. For more information, please follow other related articles on the PHP Chinese website!

    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Latest Articles by Author
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template