受Javascripts变量的启发Max()/ Min()中的变量和函数语言中的列表理解我试图在VB.NET中使用Generic Extension方法获得相同的结果,给定IEnumerable(of T)作为resulttype。这适用于字符串。为什么? 这种扩展方法可能被认为是一个坏主意。任何有力的理由为什么这是一个坏主意。
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对象编写了一些方法。
答案 0 :(得分:1)
字符串是IEnumerable<char>
,字符串和字符之间没有关系。您可以将其视为维度问题,通常可以将字符串视为char数组。 char []不等于char,也不会。 System.String还实现了一个方法Concat,它可以搞乱你的类型签名,所以你可能要小心。