c# - 非静态字段、方法或属性需要对象引用 'member'

标签 c#

`我想用静态方法更改文本框文本。考虑到我不能在静态方法中使用“this”关键字,我该怎么做。换句话说,我怎样才能对文本框文本属性进行对象引用?

这是我的代码

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public delegate void myeventhandler(string newValue);


    public class EventExample
    {
        private string thevalue;

        public event myeventhandler valuechanged;

        public string val
        {
            set
            {
                this.thevalue = value;
                this.valuechanged(thevalue);

            }

        }

    }

        static void func(string[] args)
        {
            EventExample myevt = new EventExample();
            myevt.valuechanged += new myeventhandler(last);
            myevt.val = result;
        }

  public  delegate string buttonget(int x);



    public static buttonget intostring = factory;

    public static string factory(int x)
    {

        string inst = x.ToString();
        return inst;

    }

  public static  string result = intostring(1);

  static void last(string newvalue)
  {
     Form1.textBox1.Text = result; // here is the problem it says it needs an object reference
  }



    private void button1_Click(object sender, EventArgs e)
    {
        intostring(1);

    }`

最佳答案

如果您想从静态方法内部更改非静态对象的属性,您需要通过以下几种方式之一获取对该对象的引用:

  • 对象作为参数传递给您的方法 - 这是最常见的。该对象是您的方法的参数,您可以在其上调用方法/设置属性
  • 对象设置在静态字段中 - 这个对于单线程程序是可以的,但是当你处理并发时就容易出错
  • 对象通过静态引用可用 - 这是第二种方式的概括:对象可能是单例,您可能正在运行静态注册表您可以通过名称或其他 ID 等获得对象。

在任何情况下,您的静态方法都必须获取对象的引用,以便检查其非静态属性或调用其非静态方法。

关于c# - 非静态字段、方法或属性需要对象引用 'member',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15316651/

相关文章:

c# - 事务性 CloudBlob

c# - itextsharp 渐变背景

c# - 完全删除重复的字符(正则表达式/C#)

c# - 在 WPF 中模拟按键

c# - 如何从 .NET DataGridView 控件单元格值写入文本文件?

c# - 为什么我在 Active Directory 中创建用户时得到 "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"

c# - 在远程计算机上安装 msi (ManagementException "Not found")

c# - 如何在 Global.asax 之外处理 Session.End 事件

c# Web 应用程序如何获得不包括周末和公共(public)假期的工作日

javascript - 我可以在没有相应 C# 对象的情况下在 API 上接收 JavaScript 对象吗?