【问题标题】:Calling Generic function + lambda调用通用函数 + lambda
【发布时间】:2011-08-01 15:08:22
【问题描述】:

我在 vb.net 中有这个函数,我从 C# 转换为我正在处理的项目。

Private Function GetAllFactory(Of T)(ByVal ctor As Construct(Of T)) As List(Of T)

    'TODO: Data Access stuff 
    Dim ds As New DataSet()
    Dim entities = New List(Of T)()

    For Each dataRow As DataRow In ds.Tables(0).Rows
        Dim entity As T = ctor(dataRow)
        entities.Add(entity)
    Next
    Return entities

End Function

和下面的委托

Private Delegate Function Construct(Of T)(ByVal dataRow As DataRow) As T

我尝试将代码转换为从 C# 调用函数到 vb.net

Return GetAllFactory(Of MyType)(row >= New MyType(row))

上面的行不起作用。我有点卡住了。我在 C# 中使用 lambda 的次数不多,在 vb.net 中使用得更少。

MyType 构造函数:

Public Sub New(ByVal dataRow As DataRow)
  .
  .
  .
 End Sub

关于如何调用 GetAllFactory 有什么建议吗?

【问题讨论】:

    标签: vb.net generics lambda


    【解决方案1】:

    你在VB中使用Function关键字来写一个lambda表达式:

    Return GetAllFactory(Of MyType)(Function(row) New MyType(row))
    

    请注意,>= 是比较运算符,而 => 是 C# 中的 lamda 运算符。 VB 可能会为使用 => 的代码提供一些意外的错误消息,因为它接受它作为 >= 运算符的未记录别名。

    【讨论】:

    • 太棒了!谢谢古法。 >= 当我输入 => 时自动转换(我猜是因为 vb.net 没有 => 重载,它是 >= ?)
    • @user872995:而是因为它将=> 识别为>= 的别名,因此将其更改为操作符的文档形式。
    【解决方案2】:

    VB.Net lambda 表达式如下所示:

    Return GetAllFactory(Of MyType)(Function(row) New MyType(row))
    

    【讨论】:

      猜你喜欢
      • 2021-06-04
      • 1970-01-01
      • 2015-07-04
      • 2021-09-04
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多