是否有更简单的方法将一组变量作为数组传递
我想要做的是为我的StreamWriter实例编写一个专用方法,而不是在程序中的随机点上使用它。 这会对调用类的位置进行本地化,因为当前的方法存在一些错误。
这就是我现在所拥有的:
public static void Write(string[] stringsToWrite) { writer = new StreamWriter(stream); writer.Write("hello"); foreach (string stringToWrite in stringsToWrite) { writer.Write(" " + stringToWrite + " "); } writer.Flush(); }
注意:stream是TcpClient的一个实例
有了这个我能够传递一个变量数组来写,但我不能使用与现有方法相同的方法调用:
writer.WriteLine("hello {0} {1} {2}", variable1, variable2, variable 3); writer.Flush();
如果我能够将x个变量传递给方法并且循环以这种方式编写每个变量,那将是很好的,但.NET中的可选参数直到v4.0仍然处于测试阶段才会到达。
有任何想法吗?
你可以看一下params关键字 :
public static void Write(params string[] stringsToWrite) { ... foreach (string stringToWrite in stringsToWrite) { writer.Write(" " + stringToWrite + " "); } ... }
那么用法就是你想要的。
在方法上使用params关键字:
public static void Write(params string[] stringsToWrite) {
然后你可以说
Write("Hello", "There")
你仍然可以传入一个普通的数组,就像WriteLine
会接受一个。
在大多数情况下, params
(已经提到)是明显的答案。 请注意,您也可以考虑替代方案,例如:
static void Main() { string s = Format("You are {age} years old and your last name is {name} ", new {age = 18, name = "Foo"}); }
如此处所示, 此处更多讨论。
使用params
:
public static void Write(params string[] stringsToWrite) { ... // your code here }
调用Write(a, b, c)
,这相当于Write(new string[] {a, b, c})
。
使用param数组!
public void Write(params string[] oStrings) { }