通过单击EventHandler传递字符串



我正在尝试发送3个字符串到void/EventHandler

button.Click += new DownloadGame(gameZip, gameExe, gameTitle);
private void DownloadGame(string gameZip, string gameExe, string gameTitle)
{
if (!File.Exists(gameExe))
{
MessageBox.Show("Already Installed!");
}
string GamesDirectory = Path.Combine(Environment.CurrentDirectory, "Games");
if (!Directory.Exists(GamesDirectory))
Directory.CreateDirectory(GamesDirectory);
InstallGameFiles(Path.Combine(Directory.GetCurrentDirectory(), "Build", gameExe), gameZip, gameTitle);

如何使用参数调用方法而不出现此错误?

错误CS0246类型或名称空间名称'DownloadGame'无法找到(您是否缺少using指令或程序集引用?)

你得到错误的原因CS0246.new关键字:

// I N C O R R E C T
button.Click += new DownloadGame(gameZip, gameExe, gameTitle);

由于new,编译器正在尝试创建一个名为DownloadGameclass的新实例。它找不到同名的,因为它不存在(只有同名的方法,因此出现错误)。


语法不正确的另一个原因是委托签名必须匹配。例如,Winforms按钮处理程序会这样赋值:

public MainForm()
{
buttonDownload.Click += onClickDownloadButton;
}
private void onClickDownloadButton(object sender, EventArgs e)
{
}

无论是什么平台,一旦您输入button.Click +=,智能感知应该提供一个具有正确签名的方法。

就你的代码试图做的事情而言,处理Click事件是接收Button类通知的事件和数据,而不是打算发送字符串或其他任何东西。


这里看起来有意义的事情是,您已经执行了其他UI操作来填充其中一些文件名。例如,您可能有一个按钮或菜单调用"打开文件";

设置提示符
private void onClickDownloadButton(object sender, EventArgs e)
{
DownloadGame();
}
public void DownloadGame()
{
if (!File.Exists(gameExe))
{
MessageBox.Show("Already Installed!");
}
string GamesDirectory = Path.Combine(Environment.CurrentDirectory, "Games");
if (!Directory.Exists(GamesDirectory))
{
Directory.CreateDirectory(GamesDirectory);
}
InstallGameFiles(Path.Combine(Directory.GetCurrentDirectory(), "Build", gameExe), gameZip, gameTitle);
}
// These need to be populated some other 
// way before enabling buttonDownload.    
private string gameZip;
private string gameExe;
private string gameTitle;

不能将字符串传递给单击事件。但是你可以在这个按钮所属的类下创建变量/属性。另外,当你向Event添加函数时,你不能使用'new'关键字。

string gameZip, gameExe, gameTitle; // Set those variables i.e. here
button.Click += DownloadGame;
private void DownloadGame(Object sender, EventArgs e)
{
if (!File.Exists(gameExe))
{
MessageBox.Show("Already Installed!");
}
string GamesDirectory = Path.Combine(Environment.CurrentDirectory, "Games");
if (!Directory.Exists(GamesDirectory))
Directory.CreateDirectory(GamesDirectory);
InstallGameFiles(Path.Combine(Directory.GetCurrentDirectory(), "Build", gameExe), gameZip, gameTitle);   
}

最新更新