如何将方法作为 Action 参数传递

Pha*_*rat 1 vb.net

我如何将参数作为语句传递给方法。我有一个这样的方法,我尝试在不使用 IIF 关键字的情况下将 C# 中的三元运算符刺激到 vb.net

Protected Friend Sub TernaryOperater(ByVal condition As Boolean, _
   ByVal truePart As action, Optional ByVal falsePart As action = Nothing)
  If condition Then
      truePart()
  Else
      falsePart()
  End If
End Sub
Run Code Online (Sandbox Code Playgroud)

我这样称呼这个方法:

TernaryOperater(DataGridView1.Rows.Count > 0, _
    tp21txtBillNo.Clear, tp21txtBillNo.focus)
Run Code Online (Sandbox Code Playgroud)

它在语句tp21txtBillNo.clearand下显示为红色错误颜色tp21txtBillNo.focusAction这样的声明不支持吗?

(寻找 C# 和 VB.Net 变体)

Ale*_*kov 5

在 VB/Net 中传递 Action/Func 的语法:

TernaryOperater(true, Function() OneArg(42), AddressOf   NoArgs) 
Run Code Online (Sandbox Code Playgroud)

更多信息:

首先,要成为真正的“三元运算符”(正确命名为“条件运算符”),您应该将其用作Func<T>参数,以便它可以返回结果。

Func<T>作为或传递的方法签名Action<T>应该与类型 - 不带参数的函数匹配,对于Func<T>,返回类型 T ,不带参数的函数 (sub) Action<T>。如果它不匹配 - 您可以将其与 lambda 表达式内联包装 - VB.Net 中的 lambda 表达式

C#: int Twice(int value) {return 2 * Value;} int Half(int value) {return 2 * Value;}

 T Ternary<T>(bool condition, Func<T> onTrue, Func<T> onFalse) 
 {
     return condition ? onTrue() : onFalse();
 }

 void StrangeIf(bool condition, Action onTrue, Action onFalse) 
 {
     if (condition) 
        onTrue() 
     else 
        onFalse();
 }
 ...

 StrangeIf(true, ignore => Twice(42), ignore => Halhf(42));
 var r = Ternary<int>(true, ignore => Twice(42), ignore => Halhf(42));
Run Code Online (Sandbox Code Playgroud)

VB.Net:

Function  TernaryOperater(Of T)(condition As Boolean, _
          onTrue As Func(Of T), onFalse As Func(Of T)) As T
    If condition Then
        return onTrue()
    Else
        return onFalse()
    End If
End Function

Sub StrangeIf(condition As Boolean, _
          onTrue As Action, onFalse As Action)
    If condition Then
        onTrue()
    Else
        onFalse()
    End If
End Sub

Function Twice(v as Integer)
    return v * 2
End Function

StrangeIf(true, Function() Twice(42), Function() Twice(1)) 
Run Code Online (Sandbox Code Playgroud)