开发者

Generic Concat Extension method for Paramarrays not working for IEnumerable(of String)

Inspired by Javascripts 开发者_StackOverflow社区variable Arguments in Max()/Min() and list comprehension in functional languages I tried to get the same in VB.NET using Generic Extension methods given IEnumerable(of T) as resulttype. This works well excepts for strings. Why? These kind of extension methods may be considered a bad idea. Any strong reason Why this is a bad idea.

  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

... Cut of the rest of the module for being brief. Als wrote some methods for Add, Cast and an Apply for Action objects.


A string is an IEnumerable<char>, and there's no relation between a string and char. You can think of it as a problem with dimensions, a string can usually be thought of as an array of char. char[] does not equals char, nor will it ever. System.String also implements a method Concat which can mess with your type signature so you might wanna be careful with that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜