C#接口委托事件是很重要的部分,不了解时看到会很痛苦,过了那个坎就好多了,将自己的理解记录下来,以供以后学习,查阅
1、定义接口
public interface ICal
{
///
/// 输出执行过程概要日志
///
event Action OnLogOutPut;
void Process(string msg);
}
2、定义乘法类继承接口
public class Multiply : ICal
{
#region 接口ICal
public event Action OnLogOutPut;
public void LogOutPut(string msg)
{
if(OnLogOutPut!=null)
{
OnLogOutPut(msg);
}
}
void ICal.Process(string msg)
{
LogOutPut("开始执行乘法运算");
msg = "乘法运算消息:" + msg;
LogOutPut(msg);
LogOutPut("乘法运算执行完成");
}
#endregion
}
3、定义除法类继承接口
public class Devide : ICal
{
#region 接口ICal
public event Action OnLogOutPut;
public void LogOutPut(string msg)
{
if (OnLogOutPut != null)
{
OnLogOutPut(msg);
}
}
void ICal.Process(string msg)
{
LogOutPut("开始执行除法运算");
msg = "除法运算消息:" + msg;
LogOutPut(msg);
LogOutPut("除法运算执行完成");
}
#endregion
}
4、调用类执行方法
public void Oper()
{
ICal multiply = new Multiply();
Devide dev = new Devide();
List calList = new List() { multiply, dev };
foreach (ICal cl in calList)
{
cl.OnLogOutPut += Cl_OnLogOutPut;
cl.Process(this.textBoxmsg.Text);
}
}
private void Cl_OnLogOutPut(string obj)
{
if (this.InvokeRequired)
{
this.Invoke(new Action<string>(Cl_OnLogOutPut), obj);
}
else
{
this.richTextBox1.Text += obj + Environment.NewLine;
}
}