一 : 简介
C# Action 是系统预定义的一个委托,原型为 public delegate void Action(),因此主要对象为无参数,无返回值,因此只要不追求返回值,不用自己声明委托函数,直接用Action即可。
二、使用方法:
Action a=new Action(函数名);
或者用lambda表达式:Action a=new Action( ()=>{ 执行语句 } );
扩展:
如果想带参数,就用Action<参数类型1,参数类型2,……>
例如:Action<string,string> a=new Action((a,b)=>{console.log(a+b);});
总结:
Action就是个无返回值委托,大家尽可以申明自己的委托。
为了保证代码一致性,在不同的Class中能相互识别,以及团队协作,使用统一名称的委托是十分有必要的,因此使用Action,而不自己声明独特名称的委托,可以大大提高工作效率!
二 :Event
/// <summary>
/// EventTest 的摘要说明
/// </summary>
public class EventTest
{
public delegate string Display(string str);
public delegate void GetReply(string msg);
public event Display DisplayEvent;
public event GetReply ReplyEvent;
public void Notifytion(string msg)
{
this?.DisplayEvent(msg);
}
public void NotifyUpdate(string msgg)
{
this?.ReplyEvent(msgg);
}
}
public class Listener
{
//订阅事件的处理/响应方法
public string MakeAlert(string str)
{
Console.WriteLine(str + "Listens");
return str + "Listen1";
}
}
public class MasterCommicate
{
public void MasterMsg(string mgg)
{
Console.WriteLine(mgg + " ConSole ");
}
}
三 : 调用
public class VoidMain
{
public VoidMain()
{
EventTest et = new EventTest(); //1.声明事件发布者
Listener l1 = new Listener();//2.声明订阅者
MasterCommicate l2 = new MasterCommicate();
et.DisplayEvent += l1.MakeAlert;
et.ReplyEvent += l2.MasterMsg;
et.Notifytion("Thread....");
et.NotifyUpdate("Task....");
}
}
四 : Delegate
/// <summary>
/// TActionMos 的摘要说明
/// </summary>
public class TActionMos
{
public Action<int, double, string> actionHandler;
public event Action<int, double, string> eventHandler;
public void ReceviveEventHandler(int val, double dval, string sval)
{
Console.WriteLine(val.ToString());
Console.WriteLine(dval.ToString());
Console.WriteLine(sval.ToString());
}
public void Notify()
{
this?.eventHandler(1, 2.0, "My Test Demo");
}
}
五 : 调用
public class DoMain
{
public DoMain()
{
TActionMos mos = new TActionMos();
mos.actionHandler += new Action<int, double, string>(mos.ReceviveEventHandler);
mos.eventHandler += mos.actionHandler;
mos.Notify();
Console.ReadKey();
}
}