csharp 委托是回调函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 委托是回调函数相关的知识,希望对你有一定的参考价值。

    [ComVisible(true)]
    public class EventArgs
    {
        //
        // 摘要:
        //     Provides a value to use with events that do not have event data.
        public static readonly EventArgs Empty;

        //
        // 摘要:
        //     Initializes a new instance of the System.EventArgs class.
        public EventArgs();
    }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DelegateIsEventSignature
{
    class Program
    {

        static void Main(string[] args)
        {
            Person p1 = new Person();
            p1.DoSpeakEvents += SlowSpeak;
            p1.DoSpeakEvents += LoudlySpeak;
            p1.DoIt();
            Console.ReadKey();
        }
        static void SlowSpeak(object a, EventArgs e)
        {
            Console.WriteLine("asdfasdfasdf    "+a.ToString());
        }
        static void LoudlySpeak(object a,EventArgs e)
        {
            Console.WriteLine("i am louderly speak   " + a.ToString());
        }

    }
    public class Person
    {
        public delegate void Speak(object o, EventArgs e);
        public event Speak DoSpeakEvents;
        //可以写成下面的这种格式,就不用写delegate了,简写模式
        public EventHandler<EventArgs> TestSpeak;
        //DoIt相当于Nofity,通知所有的挂载函数
        public void DoIt()
        {
            DoSpeakEvents(this, EventArgs.Empty);
        }
    }

}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DelegateIsCallBackFunction
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person();
            p1.Talk(SlowSpeak);
            Console.ReadKey();
        }
        static void SlowSpeak(int i)
        {
            Console.WriteLine(i+" i am slowly speak"+i);
        }
    }
    public class Person
    {
        public delegate void Speak(int i);
        public void Talk(Speak speak)
        {
            for (int i = 0; i < 50; i++)
            {
                speak(i);
            }
        }
    }
}

以上是关于csharp 委托是回调函数的主要内容,如果未能解决你的问题,请参考以下文章

委托

委托和回调函数例子

第十七章 委托

将成员函数用于 C 样式回调时固定委托

C语言使用回调函数模拟委托与反射

委托的来由