我有一些代码要从 VB 转换为 C#。我的一个片段似乎无法从一个转换为另一个,如果是这样,我只是不知道该怎么做,我有点沮丧。
这是一些背景:
OrderForm
是一个抽象
类,由Invoice
(以及PurchaseOrder
)继承。以下 VB 代码段可以正常工作:
Dim Invs As List(Of OrderForm) = GetForms(theOrder.OrderID)
....
Dim inv As Invoice = Invs.Find(
Function(someInv As Invoice) thePO.SubPONumber = someInv.SubInvoiceNumber)
在 C# 中,我最好的转换方法是:
List<OrderForm> Invs = GetForms(theOrder.OrderID);
....
Invoice inv = Invs.Find(
(Invoice someInv) => thePO.SubPONumber == someInv.SubInvoiceNumber);
但是,当我执行此操作时出现以下错误:
Cannot convert lambda expression to delegate type 'System.Predicate' because the parameter types do not match the delegate parameter types
有没有什么方法可以在不重构我的整个代码库的情况下解决这个问题?
最佳答案
无论何时将 VB 转换为 C#,始终打开 OPTION STRICT ON。在这种情况下,您甚至会在点击 c# 之前看到错误消息。在这种情况下,VB 将返回
Option Strict On does not allow narrowing in implicit type conversions between the lambda expression and delegate 'System.Predicate(Of OrderForm)'
从那里您可以很容易地看出您正在尝试将基类隐式转换为子类。人们在这里编写的 C# 代码是正确的,这是 VB 等效代码:
Dim inv As Invoice = DirectCast(Invs.Find(Function(someInv As OrderForm) SubPONumber = DirectCast(thePO.SubPONumber, Invoice).SubInvoiceNumber), Invoice)
更新
这是来自@Anthony Pegram 的帖子的 C# 版本:
Invoice inv = (Invoice)Invs.Find(someInv => thePO.SubPONumber == ((Invoice)someInv).SubInvoiceNumber);
此外,如果可能,我建议您对模式进行一些更改。 GetForms()
现在返回 OrderForms
但稍后您只是假设它们都是 Invoices
。希望你有一些逻辑来验证这一点。我建议 GetForms()
否则实际上返回 Invoices
。
关于c# - VB 到 C# 的转换与 lambda 不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4611235/