1

我正在尝试将一些 C# 代码转换为 VB .Net,并且遇到了一些 delgate 转换的问题。

备份库.cs

Public Class Backup
{
public event EventHandler<BackupPEventArgs> Backup;

...
if (BackupProgress != null) BackupProgress(this, new BackupProgressEventArgs(percent_complete))
...
}

public class BackupEventArgs : EventArgs
    {
        private float percentage;

        public BackupProgressEventArgs(float percentage)
        {
            this.percentage = percentage;
        }

        public float Percentage
        {
            get { return percentage; }
        }
    }

单元测试.cs

public void BackupTest()
{
Backup bu = new Backup()
        bu.BackupProgress += delegate(object sender, Backup.BackupEventArgs e)

        {
            Debug.WriteLine("Percentage: " + e.Percentage.ToString());
        };
}

它正在转换 sb.Backup += delegate(object sender, SQLBackup.BackupProgressEventArgs e) 并将其连接到我遇到问题的另一个类中的事件。

在 VB 中:

备份库.vb

Public Class Backup

Public Event Backup As EventHandler(Of BackupEventArgs)

...
RaiseEvent Backup(Me, New BackupEventArgs(percent_complete))
...
End Class

Public Class BackupEventArgs
            Inherits EventArgs

单元测试.vb

Public Class BackupTest

Dim bu As New Backup()

bu.BackupProgress = Sub(sender As Object, e As BackupEventArgs)
                         Debug.WriteLine(e.Percentage.ToString())
                         End Sub

End Class

当然

bu.BackupProgress = Sub(sender As Object, e As BackupEventArgs)
                             Debug.WriteLine(e.Percentage.ToString())
                             End Sub

是我从 C# 转换为 .Net 时遇到的问题所在。

4

1 回答 1

2

您可以在这里尝试 AddHandler

AddHandler bu.BackupProgress, AddressOf Sub(sender As Object, e As BackupEventArgs)
                         Debug.WriteLine(e.Percentage.ToString())
                         End Sub

为了让争论进来,这将无法在 VB.Net 中以这种方式保持匿名。您需要使用固定地址抽象出您的方法。

Protected Sub BackupProgressDelegate(sender as Object, e as BackupEventArgs)
    Debug.WriteLine(e.Percentage.ToString())
End Sub

...

AddHandler bu.BackupProgress, AddressOf BackupProgressDelegate
于 2012-11-08T15:59:29.697 回答