简体   繁体   中英

C# - Event/EventHandler syntax

In my ASP.NET .NET 4 book, I'm seeing this syntax:

public event EventHandler<AddressEventArgs> SaveButtonClick;

I'm not familiar with this syntax, especially the '< >' next to the event handler. Could someone please explain the above code?

Full code example from the book is below.

//Declare custom EventArgs to be used
public class AddressEventArgs : EventArgs {
    public AddressEventArgs(string addressLine1, string addressLine2,
    string city, string state, string postalCode) {
        this.AddressLine1 = addressLine1;
        this.AddressLine2 = addressLine2;
        this.City = city;
        this.State = state;
        this.PostalCode = postalCode;
    }
    public string AddressLine1 { get; private set; }
    public string AddressLine2 { get; private set; }
    public string City { get; private set; }
    public string State { get; private set; }
    public string PostalCode { get; private set; }
}

//Code in a user control raising the event on a button click
public event EventHandler<AddressEventArgs> SaveButtonClick;
protected void ButtonSave_Click(object sender, EventArgs e) {
    if (SaveButtonClick != null) {
        SaveButtonClick(this, new AddressEventArgs(TextBoxAddress1.Text,
        TextBoxAddress2.Text, TextBoxCity.Text, TextBoxState.Text,
        TextBoxPostalCode.Text));
    }
}

The '< >'s indicate that EventHandler is a generic type. If you have never been exposed to generics before I suggest you read this article:

An Introduction to C# Generics

Basically, you can think of a generic as a special class that you have the ability specify the type of object you want to store in it / have it be applicable to. Once you do that, the methods and interaction with the class is strongly typed, so you do not need to cast things, or be forced to store them as an object type.

A very commonly used generic is the List<T> type. It is similar to an array, but has a flexible size (you don't need to re-declare its size) and you have convenience methods like Add() , Remove() , RemoveAt() , etc. So a List<int> could store however many integers you want, and a List<MyClass> object would be used for storing a collection of your MyClass objects.

This syntax is called "generics". Take a look at http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx for an intro to the concept.

In this specific case, it's used to say that this event will use the AddressEventArgs class for passing details into handlers.

If you're familiar with the old .NET event syntax (before generics existed), take a look at http://codebetter.com/jpboodhoo/2007/07/11/leveraging-the-eventhandler-lt-t-gt-delegate-more-effectively for a comparison

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM