马克斯(灵感来自Javascript角可变参数)/ MIN()和函数式语言列表解析参数数组通用的毗连扩展方法我尝试使用通用扩展方法来获得同样的在VB.NET给定IEnumerable(T)作为resulttype。除了字符串,这很好。为什么? 这些扩展方法可能被认为是一个坏主意。任何有力的理由为什么这是一个坏主意。不工作的IEnumerable(字符串)
Option Explicit On
Option Strict On
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
Dim xs As IEnumerable(Of Integer) = 1.Concat(2, 3, 4)
Dim ys As IEnumerable(Of Double) = 1.0.Concat(2.0, 3.0, 4.0)
Dim zs As IEnumerable(Of String) = Concat("1", "2", "3", "4") 'silly but works, I would use a stringbuilder
'Dim zs2 As IEnumerable(Of String) = "1".Concat("2", "3", "4") ' does not work why?
'Gives:
'String' cannot be converted to 'System.Collections.Generic.IEnumerable(Of String)'
'because() 'Char' is not derived from 'String', as required for the 'Out' generic parameter 'T' in 'Interface IEnumerable(Of Out T)'.
'C:\Users\kruse\Documents\Visual Studio 10\Projects\VarArgsExperiment\VarArgsExperiment\Module1.vb 12 45 VarArgsExperiment
Console.ReadLine()
End Sub
<Extension()> _
Function Concat(Of T)(ByVal xs As IEnumerable(Of T), ByVal ParamArray params As T()) As IEnumerable(Of T)
Dim ys As IEnumerable(Of T) = params.AsEnumerable()
Return xs.Concat(ys)
End Function
<Extension()> _
Function Concat(Of T)(ByVal x As T, ByVal ParamArray params As T()) As IEnumerable(Of T)
Dim xs As New List(Of T)
xs.Add(x)
Dim ys As IEnumerable(Of T) = params.AsEnumerable
Return xs.Concat(ys)
End Function
End Module
...模块的其余部分被剪短以便简短。 Als为Add,Cast和Apply for Action对象编写了一些方法。
你真的需要调用'params.AsEnumerable()',因为它已经是'T()'类型了吗? – 2009-10-17 11:43:43