【问题标题】:Equivalent of C# BeginInvoke((Action)) in VB.NETVB.NET 中 C# BeginInvoke((Action)) 的等价物
【发布时间】:2020-08-04 11:22:57
【问题描述】:

我需要将以下 C# 代码转换为 VB.NET:

if (this.InvokeRequired)
{
    this.BeginInvoke((Action)(() =>
    {
        imageMutex.WaitOne();
        pbCamera.Image = (Bitmap)imageCamera.Clone();
        imageMutex.ReleaseMutex();
    }));
}

我试过这样:

If Me.InvokeRequired Then
    Me.BeginInvoke((Action)(Function()
        imageMutex.WaitOne()
        pbCamera.Image = CType(imageCamera.Clone(), Bitmap)
        imageMutex.ReleaseMutex()
   ))
End If

但是编译器告诉我Action 是一种类型,不能用作表达式。 这样的委托怎么会是用VB.NET写的?

【问题讨论】:

  • (Action) 是 C# 风格的转换,在 VB.NET 中不起作用。
  • 网上有免费的自动代码转换器可以帮助您。例如,codeconverter.icsharpcode.net 的转换器建议将其写为 If Me.InvokeRequired Then Me.BeginInvoke(CType((Sub() imageMutex.WaitOne() pbCamera.Image = CType(imageCamera.Clone(), Bitmap) imageMutex.ReleaseMutex() End Sub), Action)) End If
  • 没有理由将 lambda 表达式转换为 Action,对吧?你不能写:Me.BeginInvoke(Sub() ... do code in multiple lines ... End Sub) 吗?见here?我几乎认为这是我链接到的问题的重复。
  • 您确定要 BeginInvoke,而不是 Invoke?此外,对我来说,使用 InvokeRequired 来决定何时执行该处理代码,而没有 Else 是很奇怪的。
  • @djv 请参阅 Jon Skeet 在What's the difference between Invoke() and BeginInvoke() 上的回答,注意最后一段。

标签: c# vb.net anonymous-function code-translation begininvoke


【解决方案1】:

直接翻译为:

    If Me.InvokeRequired Then
        Me.BeginInvoke(DirectCast(
            Sub()
                imageMutex.WaitOne()
                pbCamera.Image = DirectCast(imageCamera.Clone(), Bitmap)
                imageMutex.ReleaseMutex()
            End Sub, 
            Action)
        )
    End If

正如其他人指出的那样,您不需要将 lambda 强制转换为 Action:

    If Me.InvokeRequired Then
        Me.BeginInvoke(
            Sub()
                imageMutex.WaitOne()
                pbCamera.Image = DirectCast(imageCamera.Clone(), Bitmap)
                imageMutex.ReleaseMutex()
            End Sub
        )
    End If

https://codeconverter.icsharpcode.net 在转换这方面做得很好。如果您在 C# 中找到所需代码但在转换的几个方面遇到问题,则可能需要考虑一些事情

【讨论】:

    猜你喜欢
    • 2011-01-27
    • 2023-03-09
    • 2016-10-14
    • 2011-05-23
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多