我有一个接受字符串数组作为参数的函数
public static void LogMethodStart(string[] parameters)
{
AddLogEntry("Starting Method", parameters); //this does not work
}
public static void AddLogEntry(string[] parameters)
{
using(StreamWriter sw = new StreamWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), FileName), true))
{
foreach (string p in parameters)
{
stream.WriteLine(p.ToString() + DateTime.Now.ToString());
}
}
}
有没有办法传递一个元素作为数组包含而不必做一些Array.resize()操作并检查null等...?
答案 0 :(得分:4)
将您的方法签名更改为:
public static void LogMethodStart(params string[] parameters)
{
AddLogEntry("Starting Method", parameters); //this does not work
}
然后你可以通过几种方式调用它:
LogMethodStart("string1","string2");
LogMethodStart(new string[] {"string1","string2"});
这两种方法在方法中看起来都是一样的。
编辑:
修改LogMethodStart正文:
var newParams = new List<string>(parameters);
newParams.Insert(0,"Starting Method");
AddLogEntry(newParams.ToArray());