简体   繁体   English

不能将类型 void 隐式转换为 int c#

[英]cannot implicitly convert type void to int c#

Hello So I am making a text editor and have two functions I call when clicking on different buttons in my GUI.你好 所以我正在制作一个文本编辑器,当点击我的 GUI 中的不同按钮时,我会调用两个函数。 So I call my "NewTextbutton" function in "CloseToolStripMenuItem" function.所以我在“CloseToolStripMenuItem”函数中调用了我的“NewTextbutton”函数。 What I want is if the user clicks on cancel my program should not close.I though I can have a returned value from the function and then with if statment check if the user clicked on cancel or not.我想要的是如果用户点击取消我的程序不应该关闭。虽然我可以从函数中获得一个返回值,然后使用 if 语句检查用户是否点击了取消。 But I get error that I cannot convert Void to int.但是我收到错误,我无法将 Void 转换为 int。 Can anyone please help.任何人都可以请帮忙。 Thanks.谢谢。

private int NewTextbutton_Click(object sender, EventArgs e)
{
    if (TextBox.TextLength==0)
    {
        TextBox.Clear();
        return 0;
    }
    else
    {

        if (this.Text.Contains("*"))
        {
            var result = MessageBox.Show("Do you want to save changes to the document?",
                 "Texteditor",
                 MessageBoxButtons.YesNoCancel,
                 MessageBoxIcon.Question);


            if (result == DialogResult.Yes)
            {
                SaveTextbutton.PerformClick();
                TextBox.Clear(); 
                this.Text = $"Texteditor                                                 dok1.txt";
                P = "";
                return 0;
            }
            else if (result == DialogResult.Cancel)
            {
                return 1;
            }
            else
            {
                TextBox.Clear();
                return 0;
            }
        }

        TextBox.Clear();
        this.Text = $"Texteditor                                                 dok1.txt";
        P = "";
        return 0;
    }
}

private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
    int a = NewTextbutton.PerformClick(); //here is the error "cannot convert void to int"
    if (a == 1)
    {
        MessageBox.Show("operation Canceled");
    }
    else
    {
        Application.Exit();
    }

}

Indeed, an event handler usually returns void not int , so you cannot use PerformClick to get a return value.实际上,事件处理程序通常返回void而不是int ,因此您不能使用PerformClick来获取返回值。

You can refactor this way, for instance :您可以通过这种方式重构,例如:

private int CheckWhatToDo() 
{
    // all the code that was in NewTextbutton_Click(object sender, EventArgs e)
}

private void NewTextbutton_Click(object sender, EventArgs e) {
    CheckWhatToDo();
}

private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
    int a = CheckWhatToDo(); 

    if (a == 1)
    {
        MessageBox.Show("operation Canceled");
    }
    else
    {
        Application.Exit();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM