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

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

问题描述

我想要做的是为我的 StreamWriter 实例编写一个专用方法,而不是在程序中的随机点使用它.这会将调用类的位置本地化,因为当前的调用方式存在一些错误.

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.

这是我目前所拥有的:

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的实例

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 中的可选参数直到 v4.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.

有什么想法吗?

推荐答案

你可以看看 参数关键字:

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天全站免登陆