2009-10-17 56 views
0

马克斯(灵感来自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对象编写了一些方法。

+0

你真的需要调用'params.AsEnumerable()',因为它已经是'T()'类型了吗? – 2009-10-17 11:43:43

回答

1

字符串是一个IEnumerable<char>,并有一个字符串,字符之间没有关系。你可以把它看作是一个维度的问题,一个字符串通常可以被认为是一个char数组。 char []不等于char,也不会。 System.String还实现了一个Concat方法,它可能会混淆你的类型签名,所以你可能想小心一点。

+1

你说得对。这是String的Concat,它给了麻烦。在另一篇关于扩展方法的文章中发现它。 – 2009-10-17 14:37:03