惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Attack and Defense Labs
Attack and Defense Labs
The GitHub Blog
The GitHub Blog
C
Check Point Blog
博客园_首页
MongoDB | Blog
MongoDB | Blog
N
Netflix TechBlog - Medium
F
Full Disclosure
Microsoft Security Blog
Microsoft Security Blog
爱范儿
爱范儿
Recent Announcements
Recent Announcements
阮一峰的网络日志
阮一峰的网络日志
G
GRAHAM CLULEY
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
T
Threat Research - Cisco Blogs
C
Cybersecurity and Infrastructure Security Agency CISA
V
Vulnerabilities – Threatpost
K
Kaspersky official blog
博客园 - 司徒正美
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
Project Zero
Project Zero
云风的 BLOG
云风的 BLOG
Cisco Talos Blog
Cisco Talos Blog
Know Your Adversary
Know Your Adversary
雷峰网
雷峰网
V
V2EX - 技术
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Spread Privacy
Spread Privacy
罗磊的独立博客
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
Security Affairs
SecWiki News
SecWiki News
Schneier on Security
Schneier on Security
O
OpenAI News
Jina AI
Jina AI
PCI Perspectives
PCI Perspectives
Cyberwarzone
Cyberwarzone
Y
Y Combinator Blog
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog RSS Feed
I
InfoQ
D
Docker
P
Palo Alto Networks Blog
Recorded Future
Recorded Future
M
MIT News - Artificial intelligence
博客园 - Franky
B
Blog
Scott Helme
Scott Helme
博客园 - 叶小钗
D
DataBreaches.Net

博客园 - zhaowt001

HTML 转 PDF Sort using in VS C#、ASP.NET获取当前应用程序的绝对路径,获取程序工作路径 (转帖) 炒股经验 完美解读Linux中文件系统的目录结构 30个优秀.net在线学习资源站点 如何删除windows service(转帖) Windows CE 电源管理(转贴) C#中获取程序当前路径的集中方法 随心所欲操作Enum枚举类型 (转贴) 远程连接SQL Server 2000服务器的解决方案 对软件的新认识 IIS 配置 - zhaowt001 - 博客园 一个程序员成长的六个阶段 优秀程序员应当具备的品质 ASP.NET的网站的设计与优化 override new 关键字的区别 解决IIS服务器Web访问提示输入密码 山东人!
EVENT
zhaowt001 · 2008-12-11 · via 博客园 - zhaowt001

How to: Publish Events that Conform to .NET Framework Guidelines (C# Programming Guide)
Example  See Also  Send Feedback 
 

The following procedure demonstrates how to add events that follow the standard .NET Framework pattern to your own classes and structs. All events in the .NET Framework class library are based on the EventHandler delegate, which is defined as follows:

public delegate void EventHandler(object sender, EventArgs e);
 
Note:
The .NET Framework 2.0 introduces a generic version of this delegate, EventHandler<(Of <(TEventArgs>)>). The following examples show how to use both versions.
 

Although events in classes that you define can be based on any valid delegate type, even delegates that return a value, it is generally recommended that you base your events on the .NET Framework pattern by using EventHandler, as shown in the following example.

To publish events based on the EventHandler pattern
(Skip this step and go to Step 3a if you do not have to send custom data with your event.) Declare your class at a scope visible to both your publisher and subscriber classes, and add the required members to hold your custom event data. In this example, a simple string is returned.

public class CustomEventArgs : EventArgs
{
    public CustomEventArgs(string s)
    {
        msg = s;
    }
    private string msg;
    public string Message
    {
        get { return msg; }
    }
}
 

(Skip this step if you are using the generic version of EventHandler<(Of <(TEventArgs>)>) .) Declare a delegate in your publishing class. Give it a name that ends with EventHandler. The second parameter specifies your custom EventArgs type.


public delegate void CustomEventHandler(object sender, CustomEventArgs a);


Declare the event in your publishing class by using one of the following steps.


If you have no custom EventArgs class, your Event type will be the non-generic EventHandler delegate. You do not have to declare it because it is already declared in the System namespace which is included when you create your C# project:


public event EventHandler RaiseCustomEvent;


If you are using the non-generic version of EventHandler and you have a custom class derived from EventArgs, declare your event inside your publishing class and use your delegate as the type:


class Publisher
{
    public event CustomEventHandler RaiseCustomEvent;
}
 
If you are using the generic version, you do not need a custom delegate. Instead, you specify your event type as EventHandler<CustomEventArgs>, substituting the name of your own class between the angle brackets.

public event EventHandler<CustomEventArgs> RaiseCustomEvent;
 

Example
The following example demonstrates the previous steps given by using a custom EventArgs class and EventHandler<(Of <(TEventArgs>)>) as the event type.

namespace DotNetEvents
{
    using System;
    using System.Collections.Generic;

    // Define a class to hold custom event info
    public class CustomEventArgs : EventArgs
    {
        public CustomEventArgs(string s)
        {
            message = s;
        }
        private string message;

        public string Message
        {
            get { return message; }
            set { message = value; }
        }
    }

    // Class that publishes an event
    class Publisher
    {

        // Declare the event using EventHandler<T>
        public event EventHandler<CustomEventArgs> RaiseCustomEvent;

        public void DoSomething()
        {
            // Write some code that does something useful here
            // then raise the event. You can also raise an event
            // before you execute a block of code.
            OnRaiseCustomEvent(new CustomEventArgs("Did something"));

        }

        // Wrap event invocations inside a protected virtual method
        // to allow derived classes to override the event invocation behavior
        protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
        {
            // Make a temporary copy of the event to avoid possibility of
            // a race condition if the last subscriber unsubscribes
            // immediately after the null check and before the event is raised.
            EventHandler<CustomEventArgs> handler = RaiseCustomEvent;

            // Event will be null if there are no subscribers
            if (handler != null)
            {
                // Format the string to send inside the CustomEventArgs parameter
                e.Message += String.Format(" at {0}", DateTime.Now.ToString());

                // Use the () operator to raise the event.
                handler(this, e);
            }
        }
    }

    //Class that subscribes to an event
    class Subscriber
    {
        private string id;
        public Subscriber(string ID, Publisher pub)
        {
            id = ID;
            // Subscribe to the event using C# 2.0 syntax
            pub.RaiseCustomEvent += HandleCustomEvent;
        }

        // Define what actions to take when the event is raised.
        void HandleCustomEvent(object sender, CustomEventArgs e)
        {
            Console.WriteLine(id + " received this message: {0}", e.Message);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Publisher pub = new Publisher();
            Subscriber sub1 = new Subscriber("sub1", pub);
            Subscriber sub2 = new Subscriber("sub2", pub);

            // Call the method that raises the event.
            pub.DoSomething();

            // Keep the console window open
            Console.WriteLine("Press Enter to close this window.");
            Console.ReadLine();

        }
    }
}

FROM  MSDN
http://msdn.microsoft.com/en-us/library/w369ty8x.aspx