Is there an easier way of passing a group of variables as an array

安稳与你 提交于 2019-12-10 17:52:42

问题


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 variables 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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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}).




回答5:


Use a param array!

public void Write(params string[] oStrings)
{
}


来源:https://stackoverflow.com/questions/1588135/is-there-an-easier-way-of-passing-a-group-of-variables-as-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!