一般性地引发和处理事件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一般性地引发和处理事件相关的知识,希望对你有一定的参考价值。
For a discussion of .NET events best-practices, see [Roy Osherove's blog post](http://weblogs.asp.net/rosherove/articles/DefensiveEventPublishing.aspx) and [this post](http://blogs.msdn.com/ericlippert/archive/2009/04/29/events-and-races.aspx). Be sure to read the comments sections for some good arguments for and against the presented methods. Also, there is a good [MSDN Magazine article on Event Accessors](http://msdn.microsoft.com/en-us/magazine/cc163533.aspx), which may be useful.Used in "Empire." The example shows an EventArgs with a DateTime object, but it could be a string or enumeration or whatever.
/// <summary> /// Generic EventArgs class to hold event data. /// </summary> /// <example> /// To create an event that sends a string (such as an error message): /// <code> /// public event EventHandler{EventArgs{string}} EventOccurred; /// EventOccurred.Raise(sender, "The event occurred"); /// </code> /// </example> /// <see cref="http://geekswithblogs.net/HouseOfBilz/archive/2009/02/15/re-thinking-c-events.aspx"/> /// <typeparam name="T">Any data</typeparam> public class EventArgs<T> : EventArgs { public T Args { get; private set; } public EventArgs(T args) { Args = args; } public override string ToString() { return Args.ToString(); } } /// <summary> /// Tell subscribers, if any, that this event has been raised. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="handler">The generic event handler</param> /// <param name="sender">this or null, usually</param> /// <param name="args">Whatever you want sent</param> public static void Raise<T>(this EventHandler<EventArgs<T>> handler, object sender, T args) { // Copy to temp var to be thread-safe (taken from C# 3.0 Cookbook - don't know if it's true) EventHandler<EventArgs<T>> copy = handler; if (copy != null) { } } class Tester { public static event EventHandler<EventArgs<DateTime>> GetTime_Rcvd; static void Main() { GetTime_Rcvd.Raise(null, MyDateTime); } }
以上是关于一般性地引发和处理事件的主要内容,如果未能解决你的问题,请参考以下文章