【问题标题】:Converting a function to vb from csharp将函数从 csharp 转换为 vb
【发布时间】:2018-10-26 10:24:15
【问题描述】:

我使用 converter.telerik.com 转换了这段代码

来自

public Decimal CartTotal()
{
   return this.Items.Sum<CartItem>((Func<CartItem, Decimal>) (x => x.Total));
}

收件人

Public Function CartTotal() As Decimal
   Return Me.Items.Sum(Of CartItem)(CType((Function(x) x.Total), Func(Of CartItem, Decimal)))
End Function 

但是编译器说

重载解析失败,因为没有可访问的“总和”接受这个 类型参数的数量。

【问题讨论】:

  • Where 在哪里?
  • 我的意思是sum,已经更正了
  • 我真的不明白为什么 C# 不只是 return this.Items.Sum(ci =&gt; ci.Total);,在这种情况下,VB 将是 Return Me.Items.Sum(Function(ci) ci.Total)
  • C# 代码应该只是this.Items.Sum(x =&gt; x.Total);。不需要其他任何东西。没有明确的类型,没有Func&lt;&gt; 语法。看起来有人使用转换器工具将 VB.NET 代码转换为 C#
  • @Smith 当我尝试使用converter.telerik 转换您的代码时,它会抛出错误Specified method is not supported. 看看@PanagiotisKanavos 评论

标签: c# vb.net code-conversion


【解决方案1】:

您只需将通用说明符放在“Sum”上即可:

Public Function CartTotal() As Decimal
   Return Me.Items.Sum(CType(Function(x) x.Total, Func(Of CartItem, Decimal)))
End Function

究竟为什么 VB 有这方面的问题,我现在不明白,但这是一个常见的问题。通常,该问题会影响任何 IEnumerable 扩展方法的使用。

【讨论】:

    【解决方案2】:

    这是一个关于它应该是什么的问题,还是关于 Telerik 转换器的问题?如果是后者,那么您可能希望使用 Telerik...

    如果是前者,那么可能

    Return (from item as CartItem in items Select item.Total).Sum()
    

    .NET Fiddle

    【讨论】:

    • 不需要查询。您可以将 lambda 传递给 Sum tath 返回 Total
    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    相关资源
    最近更新 更多