Dav*_*eer 9 c# architecture winforms
我理解事件在C#中的运作方式(在这个领域是一个公平的新手).我想要了解的是我们使用事件的原因.
您是否知道使用事件的编码良好/架构好的应用程序?
Dar*_*ark 10
提供一个具体的正常世界的例子....
你有一个表单,表单有一个列表框.列表框有一个很好的快乐课程.当用户从列表框中选择某些内容时,您想知道并修改表单上的其他内容.
没有事件:
您从列表框派生,覆盖事物以确保您的父级是您期望的表单.您重写ListSelected方法或其他东西,它操纵父窗体上的其他内容.
使用事件:您的表单侦听事件以指示用户选择了某些内容,并操纵表单上的其他内容.
不同之处在于,在无事件的情况下,您创建了一个单一用途的类,以及一个与其期望的环境紧密绑定的类.在with事件的情况下,操作表单的代码被本地化为你的表单,列表框就是一个列表框.
您可以在C#中使用Events和Delegates 实现Observer模式.
这是一篇描述这样的文章的链接:http://blogs.msdn.com/bashmohandes/archive/2007/03/10/observer-pattern-in-c-events-delegates.aspx
什么是非常有用的是一个使用事件的应用程序的非平凡的例子(猜测它真的有助于测试?)
到目前为止的想法是:
为什么要使用事件或发布/订阅?
引发事件时可以通知任意数量的类.
订阅类不需要知道节拍器(见下面的代码)如何工作,并且节拍器不需要知道它们将如何响应事件
代理人将发布者和订阅者分开.这是非常需要的,因为它使代码更加灵活和强大.节拍器可以改变它如何检测时间而不会破坏任何订阅类.订阅类可以在不打破节拍器的情况下改变他们对时间变化的响应方式.这两个类彼此独立地旋转,这使得代码更容易维护.
class Program
{
static void Main()
{
// setup the metronome and make sure the EventHandler delegate is ready
Metronome metronome = new Metronome();
// wires up the metronome_Tick method to the EventHandler delegate
Listener listener = new Listener(metronome);
ListenerB listenerB = new ListenerB(metronome);
metronome.Go();
}
}
public class Metronome
{
// a delegate
// so every time Tick is called, the runtime calls another method
// in this case Listener.metronome_Tick and ListenerB.metronome_Tick
public event EventHandler Tick;
// virtual so can override default behaviour in inherited classes easily
protected virtual void OnTick(EventArgs e)
{
// null guard so if there are no listeners attached it wont throw an exception
if (Tick != null)
Tick(this, e);
}
public void Go()
{
while (true)
{
Thread.Sleep(2000);
// because using EventHandler delegate, need to include the sending object and eventargs
// although we are not using them
OnTick(EventArgs.Empty);
}
}
}
public class Listener
{
public Listener(Metronome metronome)
{
metronome.Tick += new EventHandler(metronome_Tick);
}
private void metronome_Tick(object sender, EventArgs e)
{
Console.WriteLine("Heard it");
}
}
public class ListenerB
{
public ListenerB(Metronome metronome)
{
metronome.Tick += new EventHandler(metronome_Tick);
}
private void metronome_Tick(object sender, EventArgs e)
{
Console.WriteLine("ListenerB: Heard it");
}
}
Run Code Online (Sandbox Code Playgroud)
我在我的网站上写的全文:http://www.programgood.net/
这篇文章的一些内容来自http://www.akadia.com/services/dotnet_delegates_and_events.html
干杯.
| 归档时间: |
|
| 查看次数: |
8803 次 |
| 最近记录: |