【C#】C#委托学习
虽然做.NET这行也快2年了,但基础不太好啊,今天看了下委托方面的知识,记录下。
1.委托
总的来说,委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If-Else(Switch)语句,同时使得程序具有更好的可扩展性。
所以,引入委托后,编程人员可以把方法的引用封装在委托对象中,然后把委托对象传递给需要引用方法。
调用委托和调用方法的方式是一模一样的,代码如下:
a.代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace WForms
{
public partial class Form1 : Form
{
//定义委托
private delegate void WriteTextBox(char ch);
//声明委托
private WriteTextBox writeTextBox;
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
textBox1.Clear();
textBox1.Refresh();
// 实例化委托- 方法WriteTextBox1
writeTextBox = new WriteTextBox(WriteTextBox1);
// 委托作为参数,在方法WriteText通过委托运行WriteTextBox1方法
WriteText(writeTextBox); textBox3.Focus();
textBox3.SelectAll();
}
if (checkBox2.Checked == true)
{
textBox2.Clear();
textBox2.Refresh();
// 实例化委托 - 方法WriteTextBox2作为参数
writeTextBox = new WriteTextBox(WriteTextBox2);
// 委托作为参数,在方法WriteText通过委托运行WriteTextBox2方法
WriteText(writeTextBox);
textBox3.Focus();
textBox3.SelectAll();
}
} /**
*我们通过WriteText方法来向文本区写入内容,
*它所执行的只是抽象的”写文本“操作,至于究竟向哪个文本框写入文字,
*对于编写WriteText方法的程序来说是不知道,委托writeTextBox就像一个接口一样,
*屏蔽了操作对象的差别(方法到底是想向文本区1写入文本还是像文本区2写入文本,
*现在我方法里面不需要去关心,
*我只需要集中在实现”书写文本”这个操作,而不必纠结操作对象的选择)。
*/
private void WriteText(WriteTextBox writetextbox)
{
string data = textBox3.Text;
for (int i = ; i < data.Length; i++)
{
// 使用委托 - 通过委托的不同运行不同的方法
writetextbox(data[i]);
//间歇延时
DateTime now = DateTime.Now;
while (now.AddSeconds() > DateTime.Now) { }
}
}
//向文本区1添加字符
private void WriteTextBox1(char ch)
{
textBox1.AppendText(ch.ToString());
}
//向文本区2添加字符
private void WriteTextBox2(char ch)
{
textBox2.AppendText(ch.ToString());
}
}
}
Form1.cs
b.效果图:

2.委托链
其实委托链就是一个委托,只是包含了多个委托而已。看完下面代码,应该可以很明白。
a.代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace ConsoleApplication1
{
class Program
{
// 声明一个委托类型,它的实例引用一个方法,该方法返回一个string类型
public delegate string DelegateTest();
public static void Main(string[] args)
{
// 用静态方法来实例化委托
DelegateTest dtstatic = new DelegateTest(Program.method1); // 用实例方法来实例化委托
DelegateTest dtinstance = new DelegateTest(new Program().method2);
DelegateTest dtinstance2 = new DelegateTest(new Program().method3);
// 定义一个委托链对象,一开始初始化为null,就是不代表任何方法(我就是我,我不代表任何人)
DelegateTest delegatechain = null;
delegatechain += dtstatic;
delegatechain += dtinstance;
delegatechain += dtinstance2;
// Environment.NewLine - 换行符
Console.WriteLine(Environment.NewLine + dtstatic() + Environment.NewLine);// 隐式调用委托
Console.WriteLine(dtstatic.Invoke() + Environment.NewLine);// 显式调用委托
Console.WriteLine(Environment.NewLine + Test(delegatechain));//输出字符串
Console.Read(); }
private static string method1()
{
return "这是静态方法1";
} private string method2()
{
throw new Exception("抛出了一个异常");
} private string method3()
{
return "这是实例方法3";
}
// 测试调用委托的方法
private static string Test(DelegateTest chain)
{
if (chain == null)
{
return null;
} // 用这个变量来保存输出的字符串
StringBuilder returnstring = new StringBuilder(); // GetInvocationList方法返回一个由Delegate引用构成的数组,
//其中每一个数组都指向链中的一个委托对象。
Delegate[] delegatearray = chain.GetInvocationList(); // 遍历数组中的每个委托
foreach (DelegateTest t in delegatearray)
{
try
{
//调用委托获得返回值
returnstring.Append(t() + Environment.NewLine);
}
catch (Exception e)//异常
{
returnstring.AppendFormat("异常从 {0} 方法中抛出, 异常信息为:{1}{2}", t.Method.Name, e.Message, Environment.NewLine);
}
} // 把结果返回给调用者
return returnstring.ToString();
} }
}
Program.cs
b.效果图:

【C#】C#委托学习的更多相关文章
- 委托学习笔记后续:泛型委托及委托中所涉及到匿名方法、Lambda表达式
引言: 最初学习c#时,感觉委托.事件这块很难,其中在学习的过程中还写了一篇学习笔记:委托.事件学习笔记.今天重新温故委托.事件,并且把最近学习到和委托相关的匿名方法.Lambda表达式及泛型委托记录 ...
- C#委托学习
标签(空格分隔): C# 看Markdown效果支持的不大好. 买来<CLR Via C#>这本书很久了,一直也没有对其进行总结,看的非常凌乱,趁此机会好好总结一下,也算对C#学习的一个总 ...
- 委托学习总结(一)浅谈对C#委托理解
初入社会,对于我这个初级程序员来说要学的东西实在太多了,公司最近在做一个winform框架开发的桌面应用程序,众所周知,winform也好,webform也好,里面随处可见的事件驱动,有事件,当然也少 ...
- 委托学习总结(二)匿名方法和lambda表达式
之前总结了委托这个困惑着大多初学者的概念,继续来学习匿名方法和lambda表达式 (1)我们之前写了这样一段代码 //自定义一个委托 public delegate int Expression(in ...
- 《C#高级编程》之委托学习笔记 (转载)
全文摘自 http://www.cnblogs.com/xun126/archive/2010/12/30/1921551.html 写得不错,特意备份!并改正其中的错误代码.. 正文: 最近 ...
- C# 委托学习笔记
接触委托 代理 delegate很久啦.除了看API,Kotoba也给我讲了 .说到委托,拿下面这个小例子比较好.(14年6月26花花给我的练习) 实例:写一个方法A,定义个方法B(打印hello), ...
- JS事件委托学习(转)
JS 事件委托就是利用冒泡原理,把事件加到父级上触发,执行效果. 好处: 1.提高性能 2.新添加的元素还会有之前的事件 <</</</</li></ ...
- 委托学习续:Action、Func和Predicate
我们先看一个上一章的委托的例子: using System; using System.Collections.Generic; using System.Linq; using System.Tex ...
- C# 异步和委托学习
IAsyncResult是接口: IAsyncResult 异步设计模式通过名为 BeginOperationName 和 EndOperationName 的两个方法来实现原同步方法的异步调用,如 ...
随机推荐
- BZOJ 3238 [Ahoi2013]差异(后缀自动机)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3238 [题目大意] 给出一个串,设T[i]表示从第i位开始的后缀, 求sum(len( ...
- bzoj 1901: Zju2112 Dynamic Rankings -- 主席树,树状数组,哈希
1901: Zju2112 Dynamic Rankings Time Limit: 10 Sec Memory Limit: 128 MB Description 给定一个含有n个数的序列a[1] ...
- Uva 12889 One-Two-Three
Your little brother has just learnt to write one, two and three, in English. He has written a lot ...
- HDU 5137 How Many Maos Does the Guanxi Worth 最短路 dijkstra
How Many Maos Does the Guanxi Worth Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 512000/5 ...
- linux基础环境部署
Content 0.序 1.更新安装库 2.安装基础库 0.序 本文主要是记录php在 Centos下的安装配置 .文中如无特别说明.表示php-5.6.31代码目录. 1.更新安装库 $ yum u ...
- MySQL从库com_insert无变化的原因
大家都知道com_insert等com_xxx参数可以用来监控数据库实例的访问量,也就是我们常说的QPS.并且基于MySQL的复制原理,所有主库执行的操作都会在从库重放一遍保证数据一致,那么主库的co ...
- CentOS6安装redmine
Author: JinDate: 20140827System: CentOS release 6.5 (Final) 参考:http://www.redmine.org/projects/redmi ...
- DeJaVu update history
17.05.08 <-> Added Audi RB8 random code direct change -> Now can adapt VIN based keys or ke ...
- Run native executable in Android App
Run native executable in Android App Demo † Here's demo application called "Run Native Exe" ...
- OLEDB Excel 与C# 的数据流通方法
一. 名词解释: OleDbCommand 是对数据源执行各种操作的SQL语句或者存储过程,连接access.excel等数据文件进行数据操作时候用到的,其实和sqlcomma ...