zoukankan      html  css  js  c++  java
  • 利用自定义的Event或者使用Action实现对象之间的通信

    两个对象之间如果要进行通信,我们可以使用Event,或者是Action来解决,在实际的开发过程中,当需要在类A中调用类B中的一个异步执行的方法,然后又希望B中的方法执行完之后需要触发A类中的一些操作,这个时候我们就应该想到事件。

    通常情况下,我们了解最多的是控件的事件,然后控件的事件的触发一般都是通过外界输入来触发的,譬如鼠标点击控件触发,键盘有按键时触发。事件触发后我们就可以在注册事件的EventHandle中处理和响应事件。其实,完全也可以自己定义事件,通过代码的形式来触发事件。

    下面我通过下面的例子,介绍两种对象间通信的方法:例子非常简单

    1、新建一个Windows应用程序,在Form1上面拖放连个控件,一个用来测试自定义的Event触发的事件,一个用Action测试的。

    2、新建另一个和Form1.cs通信的类ActionEvent.cs;

    先贴上代码:

    Form1.cs:

    代码
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

    namespace EventTest
    {
        
    public partial class Form1 : Form
        {
            
    public Form1()
            {
                InitializeComponent();
            }


            
    private void button1_Click(object sender, EventArgs e)
            {
                ActionEvent demo 
    = new ActionEvent();
                
    //注册事件
                demo.EventAction += delegate
                {
                    MessageBox.Show(
    "Ok");
                };
            }

            
    private void button2_Click(object sender, EventArgs e)
            {
                ActionEvent demo 
    = new ActionEvent();
                Action sysAction 
    = delegate { MessageBox.Show("Ok"); };
                demo.SystemAction 
    = sysAction;//公用一个事件委托
            }
            
        }
    }

    EventAction.cs

    代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace EventTest
    {
        
    class ActionEvent
        {
            
    public delegate void MyAction();
            
    public event MyAction EventAction;

            
    public Action SystemAction { getset; }

            
    public ActionEvent()
            {
                System.Threading.Thread thread 
    = new System.Threading.Thread(new System.Threading.ThreadStart(Start));
                thread.Start();
            }
            
    void Start()
            {
                System.Threading.Thread.Sleep(
    3000);
                
    if (EventAction != null)
                    EventAction();
    //触发事件
                if (SystemAction != null)
                    SystemAction();
    //触发事件
            }
        }
    }

    这个例子想说明的实际就是:

    当使用Event时候,当ActionEvent类中的事件触发的时候,它将会使得所有注册过它的类中的委托或方法响应它;

    当时用Action时,其实是两个类公用了一个委托的引用,当其中一个引用触发时候,另一个当然也就同时被激发了。

    很简单的Demo,然后其实在项目中异步编程的时候经常可以排上用场的:)

              

  • 相关阅读:
    *Triangle
    Pascal's Triangle II
    Pascal's Triangle
    Merge Sorted Array
    House Robber
    Find Peak Element
    Container With Most Water
    *Next Permutation
    top命令VIRT,RES,SHR,DATA
    Octave简单使用
  • 原文地址:https://www.cnblogs.com/shineqiujuan/p/1933168.html
Copyright © 2011-2022 走看看