Is there an easier way of passing a group of variables as an array
What I'm trying to do is to write a dedicated method for my StreamWriter instance, rather than make use of it at random points in the program. This localises the places where the class is called, as there are some bugs with the current way it's done.
Here is what I have at the moment:
public static void Write(string[] stringsToWrite) {
writer = new StreamWriter(stream);
writer.Write("hello");
foreach (string stringToWrite in stringsToWrite) {
writer.Write(" " + stringToWrite + " ");
}
writer.Flush();
}
Note: stream is an instance of a TcpClient
With this I'm able to pass an array of varia开发者_开发问答bles to write, but I can't use the same method calls as with the existing method:
writer.WriteLine("hello {0} {1} {2}", variable1, variable2, variable 3);
writer.Flush();
It would be great if I was able to pass x number of variables to the method and for the loop to write each of them in this fashion, however optional parameters in .NET don't arrive till v4.0 which is still in beta.
Any ideas?
You can take a look at the params keyword:
public static void Write(params string[] stringsToWrite) {
...
foreach (string stringToWrite in stringsToWrite) {
writer.Write(" " + stringToWrite + " ");
}
...
}
Usage would be exactly what you want, then.
Use the params keyword on your method:
public static void Write(params string[] stringsToWrite) {
Then you can say
Write("Hello", "There")
You can still pass in an ordinary array, as much as WriteLine
would accept one.
params
(already mentioned) is the obvious answer in most cases. Note that you might also consider alternatives, for example:
static void Main() {
string s = Format("You are {age} years old and your last name is {name} ",
new {age = 18, name = "Foo"});
}
As shown here and discussed more here.
Use params
:
public static void Write(params string[] stringsToWrite) {
... // your code here
}
Call as Write(a, b, c)
, which would be equivalent to Write(new string[] {a, b, c})
.
Use a param array!
public void Write(params string[] oStrings)
{
}
精彩评论