从委托调用方法。 [英] Calling a method from a delegate.

查看:105
本文介绍了从委托调用方法。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从委托中调用一个方法,该委托也可以访问一些ui控件。数据采集​​过程中出现问题,只要内存缓冲区被填满就调用委托,然后我需要更新显示的一些值并记录数据。



我是什么尝试过:



I need to call a method from a delegate that can also access some ui controls. Problem occurred during data acquisition, delegate is called whenever memory buffer is filled, then I need to updated some values on display and record the data.

What I have tried:

public delegate void CallbackDelegate();

        static CallbackDelegate myDelegate;
        static int count = 0;
        static private void CallBack_DBEvent()
        {
            count++;
            Display();
            // getting error
            //An object reference is required for the non-static field, method, or property 'WindowsFormsApplication1.Form1.Display()'
        }

        public void Display()
        {
            textBox1.Text = count.ToString();
        }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            myDelegate = new CallbackDelegate(CallBack_DBEvent);
            CallBack_DBEvent();
        }

推荐答案

使用匹配的签名声明您的委托和一些目标方法

Declare your delegate and some "target" methods with matching signatures
delegate void myDelegate(string name);
static void myFunction1(string name)
    {
    Console.WriteLine("1: " + name);
    }
static void myFunction2(string name)
    {
    Console.WriteLine("2: " + name);
    }

然后打电话给他们:

Then call them:

myDelegate del = new myDelegate(myFunction1);
del("Joe Smith");
del = new myDelegate(myFunction2);
del("Mike Brown");

您也可以使用匿名方法调用它:

You can also call it with an anonymous method:

del = delegate(string name) { Console.WriteLine("Anon: " + name); };
del("Jane Doe");

或Lambda:

Or a Lambda:

del = name => { Console.WriteLine("Lambda: " + name); };
del("Mary Jane");


这篇关于从委托调用方法。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆