我无法理解这两个命令之间的区别,在我看来应该做同样的事情。如果有任何不清楚的地方,我已经发布了下面的整个代码。为什么在VB.Net中string.join返回列表对象
我在Person类中创建了两个函数,一个返回一个包含名字,中间名和姓氏的列表,另一个返回名称的连接字符串。我引用返回列表来连接下面的行字符串的函数:
FullName = String.Join(" ", Me.Get_NameList())
然而,当我打电话:
Console.WriteLine(Person1.Print_Name())
我得到什么样子的列表对象,而不是字符串:
System.Collections.Generic.List`1[System.String]
如果我改变的代码看起来像这样:
Public Function Print_Name()
Dim FullNameList As List(Of String) = Me.Get_NameList()
Dim FullName As String
FullName = String.Join(" ", FullNameList)
Return FullName
End Function
个
控制台打印:
John Q Doe
为什么我收到由第一分配列表一个变量,然后加入一个不同的答案吗?这是否与列表存储在内存中有关?
在此先感谢您的帮助。
下面是完整的代码:
Imports System
Module Module1
Sub Main()
Dim Person1 As New Person("John", "Q", "Doe")
Console.WriteLine("Get_Name Values")
Dim g1 As List(Of String) = Person1.Get_NameList()
Console.WriteLine(String.Join(" ", g1))
Console.WriteLine("Print_Name Values")
Console.WriteLine(Person1.Print_Name())
End Sub
End Module
Class Person
Private FirstName As String
Private MiddleName As String
Private LastName As String
Public Sub New(ByVal Fn As String, ByVal Mn As String, ByVal Ln As String)
FirstName = Fn
MiddleName = Mn
LastName = Ln
End Sub
Public Function Get_NameList()
Dim NameList As New List(Of String)
NameList.Add(FirstName)
NameList.Add(MiddleName)
NameList.Add(LastName)
Return NameList
End Function
Public Function Print_Name()
'Dim FullNameList As List(Of String) = Me.Get_NameList()
Dim FullName As String
FullName = String.Join(" ", Me.Get_NameList())
Return FullName
End Function
End Class
fyi - 它通常被认为是不好的做法,有没有显式返回类型的函数。可疑的设置函数的返回类型将解决您的问题,或者至少强制编译器错误,这会使问题更加明显。哦,而且你有Option Infer或Option Explicit,对不对? – 2012-02-27 15:43:30
开启'选项严格开启'。保持关闭可能会导致无法找到问题。 – Ryan 2012-02-27 15:45:36
只是一个方面的说明,但你会更好,只是在Print_Name中返回一个串联的字符串,而不是获得一个列表,然后加入它。或者使用'String.Format' – musefan 2012-02-27 15:53:23