简体   繁体   English

C# 。 有关从VB转换的代码的说明

[英]C# . Explanation about the code converted from VB

I am using a converter that converted the following VB code 我正在使用转换以下VB代码的转换器

Public Event Progress(ByVal Percent As Integer)

to C# 到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). 因此,我确切需要知道的是Progress主体(带有添加和删除)的优点是什么。 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: 这些System.Delegate.CombineSystem.Delegate.Remove调用只是执行以下操作的冗长方式:

// 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. 也许它是从编译的IL中生成的,这时看起来或多或少都是相同的。

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). 由于Progress事件和处理程序ProgressEvent未链接,因此您期望的代码将无法工作(因此,如果要拆分这些成员,则需要显式实现该事件)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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