C# 基础工具篇

C# 基础工具

1. 事件 Event

  1. 定义一个事件类
  2. 调用触发事件接口
  3. 注册触发回调函数
//定义一个事件类
public class MyEventManager
{
    private static MyEventManager instance = null;
    private MyEventManager() { }

    public static MyEventManager Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new MyEventManager();
            }
            return instance;
        }
    }
    public delegate void TestHander(string time, string message);
    public event TestHander TestEvent;

    public void TestEvent(string time, string message)
    {
        if (this.TestEvent!= null)
        {
            orderDownEvent(time, message);
        }
    }
}
//调用触发事件接口
MyEventManager.Instance.orderDownDoaction(DateTime.Now.ToString("yyyyMMddHHmmssm"), message);
MyEventManager.Instance.TestEvent += onTestEvent ;
private void containerPickStartTest(string time, string message)
{
	//避免线程冲突,开启独立线程
	Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(() =>
                {
                    //独立线程
                }));
}

2. 委托

  1. 定义一个委托类型
  2. 调用触发委托接口
  3. 注册触发回调函数
//定义一个委托类型
public delegate void ITestDelegate(string strJson, ref BackStruct result);
public class ServerService
{
    private static ServerService instance = null;
    private ServerService() { }
    public static ServerService Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new ServerService();
            }
            return instance;
        }
    }

    public ITestDelegate Test1Delegte;
    public ITestDelegate Test2Delegte;


    internal void Test1Reglster(ITestDelegate del)
    {
        Test1Delegte = del;
    }
    internal void Test2Reglster(ITestDelegate del)
    {
        Test2Delegte = del;
    }
}
//调用委托
BackStruct = new BackStruct();
ServerService.Instance.orderDownDelegte(strJson, ref back);
//注册回调函数
ServerService.Instance.Test1Reglster(new ITestDelegate (onTest1Callbcak));
ServerService.Instance.Test2Reglster(new ITestDelegate (onTest2Callbcak));
        
private void onTest1Callbcak(string strJson, ref BackStruct result)
{
   //处理逻辑test1
}
private void onTest2Callbcak(string strJson, ref BackStruct result)
{
   //处理逻辑test2
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小老鼠不吃猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值