对不起,如果这是一个愚蠢的问题。我不需要在VB.NET中写任何东西。
但是我将一个名为“name”的变量传递给一个函数,有时它可能是一个名字或两个名字等等。我想检查函数是否只有一个名字不添加逗号,如果它是2名称添加逗号。有没有办法得到有多少“名字”?
编辑:添加了我的颂歌,让我的问题更加清晰。对不起以前没做过。我的代码:
Public Function GenerateCSV(byval str as string, byval str1 as string, byval str2 as string, byval GrpName as string)
IF GroupName <> GrpName THEN
GroupName = GrpName
CSVString = ""
END IF
IF str = ""
CSVString = ""
ELSE
CSVString = CSVString & str & ", " & str1 & ", " & str2 & ", "
END IF
return CSVString
End function
谢谢!
答案 0 :(得分:1)
将它们作为List或数组传递。通过这些,您可以获得项目数量并执行您需要执行的任何处理。
Public Function DoSomething(names As IEnumerable(Of String)) As String
'Include this if there is a possibility of an names containing nothing
If names.Count = 0 Then
Return ""
End If
Dim csvString As String = names(0)
'First one is already added, loop through remaining
For i As Integer = 1 To (names.Count - 1)
csvString = csvString + ", " + names(i)
Next
Return csvString
End Function
您最好使用IEnumerable,它可以获取数组或列表等。如果你愿意,可以使用IList(Of String)或String()。
答案 1 :(得分:0)
不确定你如何处理name变量,但是如果你使用数组这可以工作......
string FullName
If name[1] != "" Then
FullName = name[0] + "," + name[1]
End If
我也不确定你想要'name'变量输出,但这会将两个名字连接起来并用逗号分隔。 FullName上的输出将是“Name,Name”
答案 2 :(得分:0)
修改
在功能输入问题的澄清之后编辑。
(我不是VB人员,但是):例如: -
Public Function GenerateCSV(byval str as string, byval str1 as string, byval str2 as string, byval GrpName as string)
Dim strAll As String
Dim strArr() As String
Dim i As Integer
Dim outStr As New System.Text.StringBuilder
strAll = str + " " + str1 + " " + str2
strAll = strAll.Trim()
strArr = strAll.Split(" ")
For i = 0 To strArr.Length - 1
if i > 0 then
outStr.Append(",")
End If
outStr.Append(strArr(i))
Next
return outStr.ToString
End Function
我确定一个VB人可以做到这一点:)
答案 3 :(得分:0)
如果您使用ParamArray处理可变数量的参数,那么您可以这样做:
Private Function ProcessNames(ByVal ParamArray asNames() As String) As String
Dim sbName As New System.Text.StringBuilder(100)
If asNames IsNot Nothing Then
For Each sName As String In asNames
If Not String.IsNullOrEmpty(sName) Then
If sbName.Length <> 0 Then
sbName.Append(", ")
End If
sbName.Append(sName)
End If
Next
End If
Return sbName.ToString
End Function
将被称为:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Debug.WriteLine(ProcessNames("name1", "name2"))
Debug.WriteLine(ProcessNames("name3"))
End Sub
产生输出:
name1, name2
name3
ProcessNames还可用于处理包含多个名称的字符串,这些名称由某个分隔符分隔,例如空格:
Debug.WriteLine(ProcessNames("name1 name2".Split(" "c)))
Debug.WriteLine(ProcessNames("name3".Split(" "c)))
产生输出:
name1, name2
name3