我正在尝试将一些C#代码转换为VB .Net,并且遇到了一些delgate转换问题。
BackupLibraries.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; }
}
}
UnitTest.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(对象发送者,SQLBackup.BackupProgressEventArgs e) 并将其连接到我遇到问题的其他课程中。
在VB中:
Backuplibraries.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
UnitTest.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的问题所在。
答案 0 :(得分: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