如何将函数作为参数传递给在 VB.NET 中接受对象的构造函数?
How to give a function as a parameter to a constructor taking an Object in VB.NET?
我在 C# 中有一个 class,我需要在 VB 中重新实现。这里只有构造函数是相关的,它看起来像这样:
public RelayCommand(Action<object> execute) : this(execute, DefaultCanExecute) { }
public ActionCommand(Action<object> exec, Predicate<object> canExec)
{
//stuff...
}
这个版本有效。好吧,我的 VB.NET 版本没有。它看起来像这样:
Public Sub New(ByVal execute As Object)
Me.New(execute, AddressOf DefaultCanExecute)
End Sub
Public Sub New(ByVal execute As Action(Of Object), ByVal canExec As Predicate(Of Object))
'stuff...
End Sub
DefaultCanExecute 是一个没有参数的私有布尔函数,总是返回 true。
当我在 C# 中尝试这个时,它有效:
var Foo = new ActionCommand(Bar);
在VB中,以下失败:
Dim Foo As VariantType = New RelayCommand(Bar)
VB 中的 Sub 看起来像这样:
Private Sub Bar(ByVal obj As Object)
'stuff...
End Sub
为了完整起见,C# 版本:
private void Bar(object obj)
{
//stuff...
}
有人知道为什么 VB 版本不起作用吗?谢谢:)
VariantType 是一个枚举,您不能将 RelayCommand class 转换为一个枚举。
使 VB 版本等同于 C# 更改
Dim Foo As VariantType = New RelayCommand(Bar)
至
Dim Foo = New RelayCommand(Bar)
这对我来说很好用 VB.NET
Public Sub New(ByVal execute As Action(Of Object))
MyClass.New(execute, AddressOf DefaultCanExecute)
End Sub
Public Sub New(ByVal execute As Action(Of Object),
ByVal canExec As Predicate(Of Object))
'stuff...
End Sub
然后像这样使用:
Private Sub Bar(ByVal obj As Object)
'stuff...
End Sub
Dim Foo As New RelayCommand(AddressOf Bar)
如果你想传递函数(指向函数的指针)作为参数使用AddressOf
关键字
我在 C# 中有一个 class,我需要在 VB 中重新实现。这里只有构造函数是相关的,它看起来像这样:
public RelayCommand(Action<object> execute) : this(execute, DefaultCanExecute) { }
public ActionCommand(Action<object> exec, Predicate<object> canExec)
{
//stuff...
}
这个版本有效。好吧,我的 VB.NET 版本没有。它看起来像这样:
Public Sub New(ByVal execute As Object)
Me.New(execute, AddressOf DefaultCanExecute)
End Sub
Public Sub New(ByVal execute As Action(Of Object), ByVal canExec As Predicate(Of Object))
'stuff...
End Sub
DefaultCanExecute 是一个没有参数的私有布尔函数,总是返回 true。
当我在 C# 中尝试这个时,它有效:
var Foo = new ActionCommand(Bar);
在VB中,以下失败:
Dim Foo As VariantType = New RelayCommand(Bar)
VB 中的 Sub 看起来像这样:
Private Sub Bar(ByVal obj As Object)
'stuff...
End Sub
为了完整起见,C# 版本:
private void Bar(object obj)
{
//stuff...
}
有人知道为什么 VB 版本不起作用吗?谢谢:)
VariantType 是一个枚举,您不能将 RelayCommand class 转换为一个枚举。
使 VB 版本等同于 C# 更改
Dim Foo As VariantType = New RelayCommand(Bar)
至
Dim Foo = New RelayCommand(Bar)
这对我来说很好用 VB.NET
Public Sub New(ByVal execute As Action(Of Object))
MyClass.New(execute, AddressOf DefaultCanExecute)
End Sub
Public Sub New(ByVal execute As Action(Of Object),
ByVal canExec As Predicate(Of Object))
'stuff...
End Sub
然后像这样使用:
Private Sub Bar(ByVal obj As Object)
'stuff...
End Sub
Dim Foo As New RelayCommand(AddressOf Bar)
如果你想传递函数(指向函数的指针)作为参数使用AddressOf
关键字