.net Framework库中的Console.WriteLine最多只支持3个参数,使用起来非常不方便,虽然C++支持一个无限参数的WriteLine,但是VB和C#和其他大量语言都不支持。现在,我编写了一个VB的函数,他利用VB、C#和JScript中参数数组的功能,实现了无限参数的WrtieLine。用VB编写的原因是VB含有许多简单的字符串函数,可以大大简化程序。而编译为组件后,C#是可以使用它的。
Public Shared Sub WriteLine(ByVal format As String, ByVal ParamArray args() As Object) '******************************************************************** '*作者:Ninputer '*日期:2001年8月27日 '* '*参数:format是输出字符串,包含输出内容的位置 '* args()是输出内容,可以有无限个参数,与format中相应的位置吻合 '*返回值:无 '*说明:提供无限参数的WriteLine方法,比System.Console更加方便 '********************************************************************
Dim sSubString, sSubStringRp As String Dim i, j As Integer
If args.Length = 0 Then Console.WriteLine(format) Else '解决无限参数的输出
If format = "" Then '如果没有字符串,则跳过循环搜索部分 Console.WriteLine("") Exit Sub End If
Try i = 1 '当前字符指针的位置 Do If format.Chars(i - 1) = "{" Then j = InStr(i, format, "}") 'j是从i开始,第一个“}”的位置
'对两个大括号中的内容进行截取 sSubString = format.Substring(i, j - i - 1) 'Like "3" sSubStringRp = format.Substring(i - 1, j - i + 1) 'Like "{3}"
'如果格式正确,就把{n}替换成所需要的内容 If IsNumeric(sSubString) Then If Int(Val(sSubString)) <> Val(sSubString) Then Throw New Exception() '跳转到Catch区域 format = format.Substring(0, i - 1) & _ Replace(format, sSubStringRp, args(CInt(Val(sSubString))).ToString, i, 1) '重新规定搜索的起点,避免重新替换 '让指针指向刚刚替换的子字符串的末尾 i += args(CInt(Val(sSubString))).ToString.Length - 1 Else Throw New Exception() '跳转到Catch区域 End If End If i += 1 Loop While i <= format.Length Catch e As Exception '抛出异常:表示输出格式字符串不正确 Throw New FormatException("输出格式不正确。") End Try Console.WriteLine(format) End If End Sub

|