logo search
CSharp_Prog_Guide

Публикация событий, соответствующих рекомендациям .Net Framework

В следующей процедуре демонстрируется, как добавлять события, соответствующие стандартному шаблону .NET Framework для пользовательских классов и структур. Все события в библиотеке классов .NET Framework основаны на делегате EventHandler, заданном следующим образом:

public delegate void EventHandler(object sender, EventArgs e);

Примечание.

.NET Framework 2.0 представляет общую версию данного делегата EventHandler<(Of <(TEventArgs>)>). В следующих примерах показано, как использовать обе версии.

Хотя события в задаваемых классах могут быть основаны на действительном типе делегата, даже на делегатах, возвращающих значение, обычно рекомендуется основывать события на шаблоне .NET Framework, используя EventHandler, как показано в следующем примере.

To publish events based on the EventHandler pattern

  1. (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; }

    }

    }

  2. (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);

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

    1. 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;

    2. 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;

      }

    3. 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;