简体   繁体   中英

C# . Explanation about the code converted from VB

I am using a converter that converted the following VB code

Public Event Progress(ByVal Percent As Integer)

to C#

public delegate void ProgressEventHandler(int Percent);
private ProgressEventHandler ProgressEvent;

public event ProgressEventHandler Progress
{
    add
    {
        ProgressEvent = (ProgressEventHandler) System.Delegate.Combine(ProgressEvent, value);
    }
    remove
    {
        ProgressEvent = (ProgressEventHandler) System.Delegate.Remove(ProgressEvent, value);
    }
}

That seems quite a lot of code. I was expecting just these 3 lines.

public delegate void ProgressEventHandler(int Percent);
private ProgressEventHandler ProgressEvent;
public event ProgressEventHandler Progress;

and then later I invoke the event in this way

void OnProgress(int p) {
    ProgressEvent?.Invoke (p);
}

So what exactly I need to know is what is the advantage of the Progress body (with add and remove). Should I stick to my own code or use the code by the converter? Which one is better?

Those System.Delegate.Combine and System.Delegate.Remove calls are just verbose ways of doing the following:

// combine
ProgressEvent += value;

// remove
ProgressEvent -= value;

Which turns the event member into the following:

private ProgressEventHandler ProgressEvent;
public event ProgressEventHandler Progress
{
    add
    {
        ProgressEvent += value;
    }
    remove
    {
        ProgressEvent -= value;
    }
}

And at that time, it's equivalent to the auto-implemented event member:

public event ProgressEventHandler Progress;

So, this is essentially just a verbose way of defining the event and event handler, but which really means just the same. I assume that the converter that you were using just uses the verbose way to be able to handle non-standard solutions easier. And maybe it is generating this from the compiled IL, at which point this all looks more or less the same.

Btw. your expected code won't work since the Progress event and the handler ProgressEvent are not linked (so if you want to split those members, you need to implement the event explicitly).

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