博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c#编程基础
阅读量:4580 次
发布时间:2019-06-09

本文共 2032 字,大约阅读时间需要 6 分钟。

 

1、什么是委托?

委托就是可以把一个方法作为一个参数带入另一个方法中去。但是委托不是一个方法,而是一种类型。

2、如何使用委托?

在使用委托的时候我们可以像使用一个类一样去实例化它,而与类不同的是。类实例化完成后就是一个对象,而委托实例化后还是一个委托。

 

3、使用委托的步骤:

例:先声明一个委托

1:   /// 
2:   /// 此处声明了一个返回值为空,参数为字符串的委托
3:   /// 
4:   /// 
5:  public delegate void MyDelegate(string str);
    

定义一个和委托一样返回值类型和参数类型的方法:

1:   public class c
2:          {
3:              public static void M1(string str)
4:              {
5:                  Console.WriteLine("这是第{0}个委托",str);
6:              }
7:              public static void M2(string str)
8:              {
9:   
10:                  Console.WriteLine("这是第{0}个委托",str);
11:              }
12:          }

调用委托实现

1:   static void Main(string[] args)
2:          {
3:              MyDelegate myDelegate1 = new MyDelegate(c.M1);
4:              myDelegate1("1");
5:              MyDelegate myDelegate2 = new MyDelegate(c.M2);
6:              myDelegate2("2");
7:              Console.Read();
8:          }

4、完整代码实现

1:  using System;
2:  using System.Collections.Generic;
3:  using System.Linq;
4:  using System.Text;
5:   
6:  namespace 委托
7:  {
8:
9:      class Program
10:      {
11:          static void Main(string[] args)
12:          {
13:              MyDelegate myDelegate1 = new MyDelegate(c.M1);
14:              myDelegate1("1");
15:              MyDelegate myDelegate2 = new MyDelegate(c.M2);
16:              myDelegate2("2");
17:              Console.Read();
18:          }
19:          /// 
20:          /// 此处声明了一个返回值为空,参数为字符串的委托
21:          /// 
22:          /// 
23:          public delegate void MyDelegate(string str);
24:          /// 
25:          ///
26:          /// 
27:          public class c
28:          {
29:              public static void M1(string str)
30:              {
31:                  Console.WriteLine("这是第{0}个委托",str);
32:              }
33:              public static void M2(string str)
34:              {
35:   
36:                  Console.WriteLine("这是第{0}个委托",str);
37:              }
38:          }
39:
40:      }
41:  }

转载于:https://www.cnblogs.com/ilooking/p/3578726.html

你可能感兴趣的文章
MyBatis笔记一:GettingStart
查看>>
查找不同的木棍
查看>>
面试题:顺时针打印矩阵
查看>>
DataSet、DataTable、DataRow、DataColumn区别及使用实例
查看>>
python 特殊方法
查看>>
Python3 练习笔记四
查看>>
装箱问题
查看>>
Android线程管理(一)——线程通信
查看>>
vim 使用技巧
查看>>
Periodic String UVa1225
查看>>
Android 演示 DownloadManager——Android 下载 apk 包并安装
查看>>
采用oracle存储过程读取excel文件更新表
查看>>
固定虚拟机中windows系统的ip地址
查看>>
【转】正则应用实例,如将多个空格改为1个空格
查看>>
移动端自动打包平台
查看>>
gradle 使用总结
查看>>
C#函数式程序设计初探——重构应用篇
查看>>
兼容的获取选择文本方法
查看>>
谈一谈git和SVN两大版本管理工具。
查看>>
【1】Bootstrap入门引言
查看>>