有路过一组变量作为数组的一个更简单的方法 [英] Is there an easier way of passing a group of variables as an array

查看:172
本文介绍了有路过一组变量作为数组的一个更简单的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的就是写一个专门的方法对我的StreamWriter实例,而不是利用它在任意点的计划。这localises其中类就是所谓的地方,因为有一些错误与目前的方式,它的完成。

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();
}

注:流是TcpClient的实例

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();

这将是巨大的,如果我能够变量x个传递给方法和循环在这种方式写他们每个人的,然而,在.NET可选参数没有到达,直到4.0版这仍然是处于测试阶段。

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.

任何想法?

推荐答案

您可以看看在的 params关键字

public static void Write(params string[] stringsToWrite) {
    ...    

    foreach (string stringToWrite in stringsToWrite) {
        writer.Write(" " + stringToWrite + " ");
    }

    ...
}

用法是你想要什么,然后。

Usage would be exactly what you want, then.

这篇关于有路过一组变量作为数组的一个更简单的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆