C# event 事件学习

C# event 事件学习函数

运行环境:Window7 64bit,.NetFramework4.61,C# 6.0; 编者:乌龙哈里 2017-02-26学习


章节:spa

  • 简单事件编写
  • 模拟 WPF 控件传递消息

正文:设计

1、简单事件编写:事件

对于 C# 中的事件 event ,个人理解是:经过委托(delegate)来调用另外一个类的 method
好比下面有个电台的类: string

class Station
{
    private string info;
    public Station(string s)=>info=s;
    public void Broadcast()=> Console.WriteLine(info);
}

it

如今手头上我有个 Radio 的类,我怎么直接调用 Station.Broadcast() 呢?
方法一,能够用反射(Reflaction),可是这样太笨重了。
方法二,在 Radio 类中直接写 Station 的实例,好比 station1.Broadcast() ,但这样的设计很不灵活,万一碰到另一个实例名叫 station2 的就歇菜了。
这时候就须要事件(event)了。下来咱们就按步骤一步一步来创建一个 Radio 的类: io

一、声明一个委托 delegate 指向想调用的方法
这里是 Broadcast()。写委托的时候注意参数必须和要调用的方法类型一致。 event

public delegate void StationBroadcast();
ast

二、用关键字 event 声明这个委托的事件。

public event StationBroadcast PlayEvent;

三、写一个方法来调用这个事件。

public void OnPlay()
{
    PlayEvent();
    Console.WriteLine();
}

好了,到这步为止,咱们就设好一个能调用 Station.Broadcast() 的类 Radio。下面是整个 Radio 类的写法:

class Radio
{
    public delegate void StationBroadcast();
    public event StationBroadcast PlayEvent;
    public void OnPlay()
    {
        PlayEvent();
        Console.WriteLine();
    }
}

下来就是如何运用了。Radio 的 PlayEvent 要加载和弃掉事件,用符号 +=,-=。

示例1:

Station fm101 = new Station("fm101 is on air ~~");
Station fm97 = new Station("~~ here is fm97");
Radio radio = new Radio();
//只加载fm101
radio.PlayEvent += fm101.Broadcast;
radio.OnPlay();
//只加载fm97
radio.PlayEvent -= fm101.Broadcast;
radio.PlayEvent += fm97.Broadcast;
radio.OnPlay();
//增长一个 fm101
radio.PlayEvent+=fm101.Broadcast;
radio.OnPlay();
//多加载一次fm101
radio.PlayEvent += fm101.Broadcast;
radio.OnPlay();

/*运行结果
fm101 is on air ~~

~~ here is fm97

~~ here is fm97
fm101 is on air ~~

~~ here is fm97
fm101 is on air ~~
fm101 is on air ~~
*/


这样写,只要符合返回值为 void 的,不带参数的函数,无论叫什么名字,咱们均可以调用。
好比咱们这个 Radio 更高级些,还能放MP3,增长一个 MP3的类:

class MP3
{
    public void Play() => Console.WriteLine("yoyo !");
}

下来咱们同样调用:

MP3 mp3 = new MP3();
radio.PlayEvent += mp3.Play;
radio.OnPlay();

/*运行结果
yoyo !
*/


2、模拟 WPF 控件传递消息:

在写 Wpf 程序的时候,Button 的响应 Click 事件通常以下:

private void Button_Click(object sender, RoutedEventArgs e);

下来咱们就模拟一下这个响应的过程。如下程序都是控制台应用,并非 Wpf 应用
首先有个消息类供控件来传递:

class MsgArgs
{
    public string str;
}

接下来 模拟窗口类 Win 里面有控件 Button,还有发生按钮 click 改变消息 MsgArgs 内容的方法:

class Win
{
    public Button button1;
    public void OnClick(object sender,MsgArgs e)
    {
        e.str = "button click";
    }
}

而后根据上面所说的步骤,创建一个 Button 类:

class Button
{
    public delegate void OnClickHandler(object o,MsgArgs e);
    public event OnClickHandler OnClick;
    public void Click(object sender,MsgArgs e)
    {
        OnClick(sender,e);
        Console.WriteLine(e.str);
    }
}

接下来就是具体调用了,以下:

Win win = new Win();
Button btn = new Button();
MsgArgs msg = new MsgArgs();

win.button1 = btn;
btn.OnClick += win.OnClick;
btn.Click(btn, msg);

模拟完毕,简单再现了 Wpf 应用中的控件消息传递。

相关文章
相关标签/搜索