Linq选择在C#和VB之间进行不同的编译

时间:2016-10-04 15:01:02

标签: c# vb.net linq

我有以下正确编译的C#代码:

private string formatterCSharp(int number)
{
    return "n" + number;
}

private void testInCSharp()
{
    IEnumerable<int> list = new List<int>();

    IEnumerable<string> formatted = list.Select(formatterCSharp);
}

如您所见,formatted应包含list的内容,并formatterCSharp应用Private Function formatterVisualBasic(ByVal number As Integer) As String Return "n" + number End Function Private Sub testInVB() Dim list As IEnumerable(Of Integer) = New List(Of Integer) Dim formatted As IEnumerable(Of String) = list.Select(formatterVisualBasic) End Sub

当我尝试在VB中复制此代码时,我想出了这个:

Select

但是我在VB中的BC30455 Argument not specified for parameter 'number' of 'Private Function formatterVisualBasic(number As Integer) As String'. BC30518 Overload resolution failed because no accessible '[Select]' can be called with these arguments: Extension method 'Public Function [Select](Of TResult)(selector As Func(Of Integer, TResult)) As IEnumerable(Of TResult)' defined in 'Enumerable': Type parameter 'TResult' cannot be inferred. Extension method 'Public Function [Select](Of TResult)(selector As Func(Of Integer, Integer, TResult)) As IEnumerable(Of TResult)' defined in 'Enumerable': Type parameter 'TResult' cannot be inferred. 语句中遇到两个编译错误。

assert false : 'If you see me, colons are allowed!

2 个答案:

答案 0 :(得分:3)

尝试

Dim formatted As IEnumerable(Of String) = list.Select(AddressOf formatterVisualBasic)

在VB.net中,您无法指定函数名称来传递它。

https://msdn.microsoft.com/en-us/library/y72ewk2b.aspx

答案 1 :(得分:0)

好的首先,选择查询在VB.NET中的形式不同,这里应该看起来如何:

    Dim formatted As IEnumerable(Of String) = list.Select(Function(x As String) x = formatterVisualBasic(mynumber))

其次,如果您想获得与C#代码相同的异常,则必须在函数调用 formatterVisualBasic 中添加括号,以便将其识别为函数

    Dim formatted As IEnumerable(Of String) = list.Select(Function(x As String) x = formatterVisualBasic())