C#学习笔记——委托
2010-06-28 20:29
309 查看
委托是一种安全地封装方法的类型,它与 C 和 C++ 中的函数指针类似。但是又有点不同C++里面函数指针只能指向静态方法,而C#里面的委托是一种可以指向任何方法的对象。首先我们来看一下委托的简单用法:
以上是调用类内部的方法,如果是掉用别的类的方法呢?首先肯定是要讲那个类实例化,在实例化委托了。我们来看下面这个例子。
委托还能够通过函数参数传递:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace test { public delegate void Eatdelegate(string food); public class Test { static void eatFood(string food) { Console.WriteLine("张三吃"+food); } static void main(string[] args) { Eatdelegate zs=new Eatdelegate(eatFood); zs("苹果"); } } }
以上是调用类内部的方法,如果是掉用别的类的方法呢?首先肯定是要讲那个类实例化,在实例化委托了。我们来看下面这个例子。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace test { public delegate void Eatdelegate(string food); public class Man { private string name; public Man(string Name) { this.name = Name; } public void eatFood(string food) { Console.WriteLine(this.name +" "+"eat"+" "+ food); } } class Test { Man m=new Man("zhangsan"); Eatdelegate zs=new Eatdelegate(m.eatFood); zs("香蕉"); } }
委托还能够通过函数参数传递:
using System; using System.Collections.Generic; using System.Linq; using System.Text; /*这个程序是关于委托的,首先我们应该知道委托相当于一个类。委托实际上是指向方法的引用 *相当于C++里面的函数指针,但是又有点不同,C++里面的函数指针只能指向静态方法,而委托 *可以指向任何方法。我们用委托来调用方法,首先应该创建委托的实例让被调用方法与之联系 *起来。再用委托的实例来调用该方法。 */ namespace test5 { public delegate void Eatdelegate(string food); public class Man { private string name; public Man(string Name) { this.name = Name; } public void eatFood(string food) { Console.WriteLine(this.name +" "+"eat"+" "+ food); } } class Program { static void eatTother(string food,params Eatdelegate[] ed) { if (ed == null) { Console.WriteLine("over"); } else { Eatdelegate eatChain = null; foreach(Eatdelegate s in ed) eatChain+=s; eatChain(food); Console.WriteLine(); } } static void Main(string[] args) { Man zs = new Man("zhangsan"); Man li = new Man("lisi"); Man ww = new Man("wangwu"); Eatdelegate ZS = new Eatdelegate(zs.eatFood); Eatdelegate LS = new Eatdelegate(li.eatFood); Eatdelegate WW = new Eatdelegate(ww.eatFood); Console.WriteLine("zhangsan,lisi,wangwu had a meeting."); eatTother("apple", ZS, LS, WW); Console.WriteLine("lisi has gone."); eatTother("banana", ZS, WW); Console.ReadKey(); } } }
相关文章推荐
- C#学习笔记(10)——再谈委托,不同国家问候的例子
- C#学习笔记-委托,event
- c#网络编程学习笔记01_委托
- 学习笔记之---C#中的委托与事件
- 学习笔记之---C#中的委托与事件
- [学习笔记]c#中的委托、事件、Func、Predicate、Observer设计模式以及其他
- C#学习笔记(31)——委托窗体传值
- C#学习笔记(8)——委托应用(显示,写入时间)
- [C#]C#学习笔记-委托,事件
- C#学习笔记:泛型委托Action<T>和Fun<TResult>
- C#学习笔记之多播委托
- C#委托与事件学习笔记
- c# 委托的学习笔记(附代码)
- C#学习笔记-delegate 委托
- C#事件 委托 学习笔记
- C#学习笔记一:委托、匿名函数、Lambda 表达式
- C#学习笔记--详解委托,事件与回调函数
- C#学习笔记19-委托和事件
- CLR Via C#系列学习笔记之委托
- C#学习笔记之一:委托