gpt4 book ai didi

c# - 如何将委托(delegate)从 c# 转换为 vb.net?

转载 作者:行者123 更新时间:2023-11-30 18:56:00 26 4
gpt4 key购买 nike

我有这段代码,我正在尝试将其从 C# 转换为 VB.net:

public object Invoke(object instance, object[] inputs, out object[] outputs)
{
// Create a new, STA thread
object[] staOutputs = null;
object retval = null;
Thread thread = new Thread(
delegate(){
retval = _innerInvoker.Invoke(instance, inputs, out staOutputs);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
outputs = staOutputs;
return retval;
}

整个委托(delegate)的事情让我失望。谁能帮我转换这个?或者是否有一篇文章解释了如何做?

最佳答案

这是一个匿名函数,VB.Net 不支持这样的匿名函数(假设是 .Net 2.0,因为在 .Net 3.5 中,它会被写成 lambda 表达式)。

您在 VB.Net 中可以做的最好的事情是将匿名函数(委托(delegate))作为单独的方法添加到同一类中,并使用 AddressOf 运算符来引用这个新方法。


更新:
再次阅读您的代码,翻译很复杂,因为您的匿名方法将被解释为闭包,这意味着 C# 编译器在将代码转换为 IL 之前会对代码进行复杂的转换;创建一个全新的类是为了捕获(关闭)方法中引用的局部变量:

Class InnerInvokerClosure
Public instance As Object
Public inputs() As Object
Public staOutputs() As Object
Public retValue As Object

Public _innerInvoker As SomeDelegateType

Sub New(ByRef instance as Object, ByRef inputs() as Object, ByRef staOutputs() As Object, ByRef retValue As Object, ByRef _innerInvoker As SomeDelegateType)
Me.instance = instance
Me.inputs = inputs
Me.staOoutputs = staOutputs
Me.retValue = retValue

Me._innerInvoker = _innerInvoker
End Sub

Public Function Invoke() As Object
retValue = _innerInvoker.Invoke(instance, inputs, staOutputs);
End Function

End Class

Public Function Invoke(ByVal instance As Object, ByVal inputs() as Object, ByRef outputs() As Object) As Object
Dim closure As New InnerInvokerClosure(instance, inputs, Nothing, Nothing, _innerInvoker)

Dim t As New Thread(AddressOf closure.Invoke)
t.SetApartmentState(ApartmentState.STA)
t.Start()
t.Join()

outputs = closure.staOutputs
return closure.retValue
End Function

请注意,此翻译未经测试且可能是错误的:确切的转换可能非常复杂。

关于c# - 如何将委托(delegate)从 c# 转换为 vb.net?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1322880/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com