string.Join()无法按预期工作

时间:2014-12-23 06:18:57

标签: .net vb.net string linq

enter image description here这里感觉有点愚蠢。也许我错过了一些东西,但为什么以下简单的呼叫没有按预期工作:

String.Join(" ", "CSharp".ToCharArray())

你希望它返回" C S h a r p",但有趣的是它返回" CSharp"。此外,以下调用返回正确的结果:

String.Join(" ", "CSharp".ToCharArray().ToList())

2 个答案:

答案 0 :(得分:2)

以下在C#

中返回true
var result = String.Join(" ", "CSharp".ToCharArray()) == String.Join(" ", "CSharp".ToCharArray().ToList());

这在vb.net中返回false

Dim result = String.Join(" ", "CSharp".ToCharArray()) = String.Join(" ", "CSharp".ToCharArray().ToList())

vb.net中似乎String.Join(" ", "CSharp".ToCharArray())正在使用

Shared Function Join ( separator As String, ParamArray value As String() )

即将"CSharp".ToCharArray()转换为1个单字符串


IL for VB.net String.Join(" ", "CSharp".ToCharArray())

IL_0001:  ldstr       " "
IL_0006:  ldc.i4.1    
IL_0007:  newarr      System.String
IL_000C:  stloc.1     // VB$t_array$S0
IL_000D:  ldloc.1     // VB$t_array$S0
IL_000E:  ldc.i4.0    
IL_000F:  ldstr       "CSharp"
IL_0014:  callvirt    System.String.ToCharArray
IL_0019:  newobj      System.String..ctor
IL_001E:  nop         
IL_001F:  stelem.ref  
IL_0020:  nop         
IL_0021:  ldloc.1     // VB$t_array$S0
IL_0022:  call        System.String.Join
IL_0027:  stloc.0     // result

IL for C#String.Join(" ", "CSharp".ToCharArray())

IL_0001:  ldstr       " "
IL_0006:  ldstr       "CSharp"
IL_000B:  callvirt    System.String.ToCharArray
IL_0010:  call        System.String.Join
IL_0015:  stloc.0     // result

答案 1 :(得分:1)

Visual Basic正在深入了解实际使用的参数。

在VB中,Char()实际上与String相同。以此代码为例:

Module Module1

    Sub Test(s As String)
        Console.WriteLine(s)
    End Sub

    Sub Main()
        Dim foo As Char() = "CSharp".ToCharArray()
        Dim foo2 As String = "CSharp"

        Test(foo)
        Test(foo2)

        Dim equal As Boolean = foo = foo2
        Console.WriteLine(equal) 
    End Sub
End Module

Visual Basic允许将Char()作为字符串传递给方法。这会导致String.Join丢失,因为它使用了错误的参数。我会尝试使用List(Of T)代替Char()

请记住,确实没有String.Join( String, Char() )超载。有Join(Of T)但是,我似乎无法让编译器让我实际设置T