简体   繁体   中英

Visual Studio's C# automated event handlers generation. Why does it create a new delegate?

When I write _exporter.csvRowProcessed += , Visual Studio 2010 offers me to create a method to handle said event, and then proceeds to do this:
_exporter.csvRowProcessed += new CsvRowProcessedHandler(RowProcessedHandler);

What I wanted to know is, why does it create a new delegate and then assigns it a handler method, instead of just assigning the handler method directly to the event like this?

exporter.csvRowProcessed += RowProcessedHandler;

Here is the whole code just in case.

    private void bg_DoWork(object sender, DoWorkEventArgs e)
    {
        object[][] data = _grid.AsMatrix();
        _exporter.csvRowProcessed += new CsvRowProcessedHandler(RowProcessedHandler);
        string csv = _exporter.CreateCSVString(data);

        StreamWriter writer = new StreamWriter(_path, false);
        writer.Write(csv);
        writer.Close();
    }

    void RowProcessedHandler(object o, int currentRow)
    {
        radProgressBarElement.Text = "Procesando linea " + currentRow;
        radProgressBarElement.Value1 = currentRow;
    }

Both forms create a new delegate instance . They're equivalent in the generated code, as far as I'm aware.

While I prefer the method group conversion too, I suspect this wasn't (before VS 2012, as noted in the comment) changed simply because there wasn't enough benefit from doing so. Indeed, some people may even prefer the more explicit form which shows the type of the delegate being created.

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