C#中Delegate委托的使用
2013-09-22 12:19
357 查看
由于我是艺术院校毕业生,死记硬背那些冷冰冰的代码对我而言实在太痛苦了,所以我都采取较为形象的记忆方式,希望这样对其他人在记忆上也会有帮助。
委托:
委托一般用于创造事件,但是单个使用的时候通常是用于将代码简洁化,委托能够将多个需要传递相同变量类型的函数通过一个委托去进行切换,从而达到简化代码的效果。
假定名为有个David的侦探,他的具体工作内容有: 找寻失物, 跟踪探索 两个工作内容,但是他对于这些工作内容不外乎就是需要一个参数,目标。
private delegate void Detective ( string target ) ;
private Detective David ;
接下来编写他的工作内容,主要有两个:
private string SearchForMissingThing ( string target ) { return "I found " + target ; } private string TrackingSomeOne ( string target ) { return "I know " + target + " is doing something" ; }
并且我们用枚举Request把工作名称记录起来:
public enum Request { SearchForMissingThing, TrackingSomeOne };
好了,现在侦探也有了,具体工作内容也有了,接下来就只剩下开设柜台以方便接收工作内容:
public void GetRequest ( Request request, string target ) { switch ( request ) { case Request.SearchForMissingThing: david = new Detective ( SearchForMissingThing ) ; break; case Request.TrackingSomeOne: david = new Detective ( TrackingSomeOne ) ; break; } GetAnswer () ; }
private void GetAnswer () { Debug.Log ( david ( target ) ) ; }
完整代码如下:
//DetectiveAgency.cs public class DetectiveAgency { private delegate string Detective ( string target ) ; private Detective david ; public void GetRequest ( Request request, string target ) { switch ( request ) { case Request.SearchForMissingThing: david = new Detective ( SearchForMissingThing ) ; break; case Request.TrackingSomeOne: david = new Detective ( TrackingSomeOne ) ; break; } GetAnswer ( target ) ; } private void GetAnswer ( string target ) { Debug.Log ( david ( target ) ) ; } private string SearchForMissingThing ( string target ) { return "I found " + target ; } private string TrackingSomeOne ( string target ) { return "I know " + target + " is doing something secret" ; } }
接下来我们通过外部调用,对David赋予一个工作内容,并在最后给我返回我想要知道的内容。接下来就简单了,新建一个脚本,并取名为DoingRequest,具体代码如下:
//DoingRequest.cs public class DoingRequest:MonoBehaviour { private DetectiveAgency Agent = new DetectiveAgency () ; void Start () { Agent.GetRequest ( Request.SearchForMissingThing, "Diamond" ) ; Agent.GetRequest ( Request.TrackingSomeOne, "Alan" ) ; } }
然后输出:
我也仍然在学习阶段,若有不对的地方还需多多指教
相关文章推荐
- c#事件处理中事件信息EventArgs的使用和类型内部事件委托delegate的调用
- C# EventHandler and Delegate(委托的使用)
- C#委托delegate使用
- C#使用委托(delegate)实现在两个form之间传递数据的方法
- C# EventHandler and Delegate(委托的使用)
- 【C#】delegate委托的定义和使用方法
- C#_delegate - 用委托实现事件,Display和Log类都使用Clock对象
- C# 委托(delegate)的使用
- C# 委托使用详解(delegate)
- c# 委托:Delegate,Action,Func,Predicate的使用与区别
- C# 委托(Delegate)使用
- C# 委托delegate使用方法
- C# EventHandler and Delegate(委托的使用)
- 关于C#的delegate(委托)和event(事件)的使用
- C# 委托(delegate)使用之一二三步
- C# EventHandler and Delegate(委托的使用)
- C# EventHandler and Delegate(委托的使用)
- C#_delegate - Pair<T> & 简单顺序逆序 & 方法委托(在Pair类下)&枚举类型 混搭使用
- C# EventHandler and Delegate(委托的使用)
- C# delegate 的使用