一般性地引发和处理事件

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.
  1. /// <summary>
  2. /// Generic EventArgs class to hold event data.
  3. /// </summary>
  4. /// <example>
  5. /// To create an event that sends a string (such as an error message):
  6. /// <code>
  7. /// public event EventHandler{EventArgs{string}} EventOccurred;
  8. /// EventOccurred.Raise(sender, "The event occurred");
  9. /// </code>
  10. /// </example>
  11. /// <see cref="http://geekswithblogs.net/HouseOfBilz/archive/2009/02/15/re-thinking-c-events.aspx"/>
  12. /// <typeparam name="T">Any data</typeparam>
  13. public class EventArgs<T> : EventArgs
  14. {
  15. public T Args { get; private set; }
  16. public EventArgs(T args)
  17. {
  18. Args = args;
  19. }
  20. public override string ToString()
  21. {
  22. return Args.ToString();
  23. }
  24. }
  25. /// <summary>
  26. /// Tell subscribers, if any, that this event has been raised.
  27. /// </summary>
  28. /// <typeparam name="T"></typeparam>
  29. /// <param name="handler">The generic event handler</param>
  30. /// <param name="sender">this or null, usually</param>
  31. /// <param name="args">Whatever you want sent</param>
  32. public static void Raise<T>(this EventHandler<EventArgs<T>> handler, object sender, T args)
  33. {
  34. // Copy to temp var to be thread-safe (taken from C# 3.0 Cookbook - don't know if it's true)
  35. EventHandler<EventArgs<T>> copy = handler;
  36. if (copy != null)
  37. {
  38. copy(sender, new EventArgs<T>(args));
  39. }
  40. }
  41.  
  42. class Tester
  43. {
  44. public static event EventHandler<EventArgs<DateTime>> GetTime_Rcvd;
  45.  
  46. static void Main()
  47. {
  48. GetTime_Rcvd.Raise(null, MyDateTime);
  49. }
  50. }

以上是关于一般性地引发和处理事件的主要内容,如果未能解决你的问题,请参考以下文章

如何编写 C++ 代码来处理 C# 代码中引发的事件

从事件处理程序确定发送者对象

在多窗口 UWP 应用中引发和处理事件

如何处理片段上的触摸事件?

如何从 C++ 代码引发事件并在另一个进程的 C# 代码中调用处理程序?

处理和引发事件