我看到了几个先前已经回答过的关于在C#中向IEnumerable添加项目的问题,但是当我试图在VB.NET中实现所提出的解决方案时,我感到困惑.
Option Strict On
Dim customers as IEnumerable(Of Customer)
' Return customers from a LINQ query (not shown)
customers = customers.Concat(New Customer with {.Name = "John Smith"})
Run Code Online (Sandbox Code Playgroud)
上面的代码给出了错误:
Option Strict On禁止从Customer到IEnumerable(Of Customer)的隐式转换
然后VS2008建议使用CType,但这会导致运行时崩溃.我错过了什么?
One option is to write an extension method which concats a single element
<Extension()> _
Public Function ConcatSingle(Of T)(ByVal e as IEnumerable(Of T), ByVal elem as T) As IEnumerable(Of T)
Dim arr As T() = new T() { elem }
Return e.Concat(arr)
End Function
...
customers = customers.ConcatSingle(New Customer with {.Name = "John Smith"})
Run Code Online (Sandbox Code Playgroud)