【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 4213 贪吃蛇 上下界费用流 网络流
https://darkbzoj.cf/problem/4213 https://www.cnblogs.com/DaD3zZ-Beyonder/p/5733326.html 题目描述 dbzoj又崩 ...
- 20162303 解读同伴的收获&解决同伴的问题 周三补交
解读同伴的收获&解决同伴的问题 11月29号 解决同伴的问题 我的同组同学是20162307学号张韵琪同学 同组同学的问题是动态规划算法步骤中递归定义的最优值 我理解他的意思是她不太理解最优值 ...
- hdu 3879 方案选择
每日一水--- #include <cstdio> #include <cstring> #include <vector> #define oo 0x3f3f3f ...
- UVA 11945 Financial Management 水题
Financial Management Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 acm.hust.edu.cn/vjudge/problem/vis ...
- SGU 406 Goggle
406. Goggle Time limit per test: 0.25 second(s)Memory limit: 65536 kilobytes input: standardoutput: ...
- C# 7.0特性与vs2017
下面是关于在C#7.0语言中计划功能的说明.其中大部分功能在Visual Studio “15” Preview 4中能运行.现在是最好的试用时期,请记录下你们的想法. C#7.0语言增加了许多的新功 ...
- .net mvc控制器传递方法到视图
很多人都是在视图里面定义方法,然后再使用.我个人也是这么干的.但是为了验证是否可以将方法从控制器传递到视图,所以做了个测试.结果真的可以.原理是利用了委托(delegate),因为委托本身就是一种类型 ...
- 模仿JQuery 的添加多个事件的原理
var jquery=function(dom){ var obj={ ready:function(fn){ if(typeof dom.onload=="function"){ ...
- PowerDesigner导出表为Excel(转)
打开脚本运行器Ctrl+Shift+X 导出: '*************************************************************************** ...
- shell中set的用法(转)
使用set命令可以设置各种shell选项或者列出shell变量.单个选项设置常用的特性. 在某些选项之后-o参数将特殊特性打开.在某些选项之后使用+o参数将关闭某些特性, 不带任何参数的set命令将显 ...