不能使用可变参数函数作为 Action 的参数 C# [英] Can't use variadic-function as Action's parameter C#
问题描述
需要找到一种方法将带有可变数量参数的委托Action(参见下面的MyLog
)传递给另一个方法(参见ExtractToDirectory
低于 MyLog
).
Need to find a way to pass a delegate Action with a variable number of parameters (see MyLog
below) to another method (see ExtractToDirectory
below MyLog
).
我有一个日志方法:
public static void MyLog(string variable, params object[] args)
{
textBoxLog.AppendText(string.Format(message, args) + Environment.NewLine);
}
在同一个 WinForm 类中进一步调用:
And a call further in the same WinForm class:
private void buttonInstall_Click(object sender, EventArgs e)
{
using (Stream zipStream = <Get stream from Resources>)
using (ZipArchive zip = new ZipArchive(zipStream))
zip.ExtractToDirectory(@"Z:\", MyLog);
}
带有方法的静态类:
public static class ZipFileExtensions
{
public static void ExtractToDirectory(this ZipArchive source, string destinationDirectoryName, Action<string, params object[]> myLog)
{
myLog("Starting {0} extraction", source.Name);
}
}
问题在于ExtractToDirectory
的声明.params
关键字带有下划线并带有错误:Type expected.
The problem is with the declaration of ExtractToDirectory
.
The params
keyword gets underlined with error : Type expected.
我尝试不输入参数,但是 VS 需要一个对象数组而不是我需要的可变长度参数.
I tried not to put params, but then VS expects an object array instead of variable length parameters as I need.
有什么线索吗?
推荐答案
Following quetzalcoatl answer,我最终得到了这个:
Following quetzalcoatl answer, I ended up with this:
public partial class MainForm : Form
{
public delegate void LogAction(string message, params object[] args);
public void Logger(string message, params object[] args)
{
if (args != null)
textBoxLog.AppendText(string.Format(message, args) + Environment.NewLine);
else
textBoxLog.AppendText(message + Environment.NewLine);
Application.DoEvents();
}
private void buttonInstall_Click(object sender, EventArgs e)
{
Logger("Button clicked");
using (Stream zipStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(MethodBase.GetCurrentMethod().DeclaringType.Namespace + ".Resources.test.zip"))
using (ZipArchive zip = new ZipArchive(zipStream))
zip.ExtractToDirectory(Program.DestinationInstallation, Logger);
}
<小时>
public static class ZipFileExtensions
{
public static void ExtractToDirectory(this ZipArchive source, string destinationDirectoryName, MainForm.LogAction myLogger)
{
int number = 20180803;
myLogger("{0} >> {1} (ok)", DateTime.Now, number);
}
}
<小时>
非常感谢帮助.
Help was much appreciated.
这篇关于不能使用可变参数函数作为 Action 的参数 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!