c# .net 委托delegate

概述

本篇你将会学到以下3大知识点

1 委托的声明、实例化和调用

2 委托的意义:解耦

3 泛型委托--Func Action

委托也是无处不在

Func Action 异步多线程 事件

如果需要定义委托 就用Func Action

Framework1.0 ----4.7  Core到处都是委托

一、委托声明

1.必须用 修饰关键词delegate 

2.用关键词delegate修饰后的,在VS里TA的着色和类的着色一致,我们用反编译工具(ILSpy)看的时候,在IL里他就是一个类

3.声明的委托和方法类似,但他有dalegate修饰

4.委托和方法一样可以带返回值和参数

5.委托可以定义在类的外面,也可以定义在类的里面。(我们大都是定义在类的里面)

    //在类外面声明一个委托
    public delegate void NoReturnNoParaOutClass();
    public class MyDelegate //: System.MulticastDelegate
    {
        /// <summary>
        /// 1 委托在IL就是一个类
        /// 2 继承自System.MulticastDelegate 特殊类-不能被继承
        /// </summary>

        //在类里面声明的委托
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个使用.NET Framework 3.5实现异步编程的示例: ```csharp using System; using System.Threading; class Program { static void Main(string[] args) { Console.WriteLine("Main thread started."); // 使用委托和回调函数实现异步编程 Console.WriteLine("Using delegate and callback to implement asynchronous programming."); MyDelegate myDelegate = new MyDelegate(DoSomething); myDelegate.BeginInvoke(5000, new AsyncCallback(Callback), null); // 使用线程池实现异步编程 Console.WriteLine("Using thread pool to implement asynchronous programming."); ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomethingThreadPool), 3000); // 使用异步方法实现异步编程 Console.WriteLine("Using async method to implement asynchronous programming."); DoSomethingAsync(2000); Console.WriteLine("Main thread ended."); Console.ReadLine(); } // 定义委托和回调函数 public delegate void MyDelegate(int milliseconds); public static void DoSomething(int milliseconds) { Console.WriteLine("DoSomething started."); Thread.Sleep(milliseconds); Console.WriteLine("DoSomething completed."); } public static void Callback(IAsyncResult ar) { Console.WriteLine("Callback started."); MyDelegate myDelegate = (MyDelegate)ar.AsyncState; myDelegate.EndInvoke(ar); Console.WriteLine("Callback completed."); } // 使用线程池 public static void DoSomethingThreadPool(object state) { Console.WriteLine("DoSomethingThreadPool started."); int milliseconds = (int)state; Thread.Sleep(milliseconds); Console.WriteLine("DoSomethingThreadPool completed."); } // 使用异步方法 public static async void DoSomethingAsync(int milliseconds) { Console.WriteLine("DoSomethingAsync started."); await Task.Run(() => Thread.Sleep(milliseconds)); Console.WriteLine("DoSomethingAsync completed."); } } ``` 该示例使用了三种不同的方法来实现异步编程:使用委托和回调函数、使用线程池、使用异步方法。在每种方法中,都使用Thread.Sleep方法模拟耗时操作。注意,在使用异步方法时,需要使用async和await关键字来标记异步方法和等待异步操作完成。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橙-极纪元JJY.Cheng

客官,1分钱也是爱,给个赏钱吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值