[英]cannot implicitly convert type void to int c#
你好 所以我正在制作一個文本編輯器,當點擊我的 GUI 中的不同按鈕時,我會調用兩個函數。 所以我在“CloseToolStripMenuItem”函數中調用了我的“NewTextbutton”函數。 我想要的是如果用戶點擊取消我的程序不應該關閉。雖然我可以從函數中獲得一個返回值,然后使用 if 語句檢查用戶是否點擊了取消。 但是我收到錯誤,我無法將 Void 轉換為 int。 任何人都可以請幫忙。 謝謝。
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();
}
}
實際上,事件處理程序通常返回void
而不是int
,因此您不能使用PerformClick
來獲取返回值。
您可以通過這種方式重構,例如:
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.