[英]} Expected in Routine
我是一名學生,目前正在學習 C#。 我嘗試編寫這個例程,但我收到一個錯誤,告訴我需要一個“}”。 但是,當我添加“}”時,我會遇到很多其他錯誤。 我認為這是因為您沒有在“else”語句之前添加“}”。 這是我的代碼:
private void PathExist()
{
if (Directory.Exists(folderBrowserDialog.SelectedPath + @"\"))
lblExist.Visible = false;
Properties.Settings.Default.FirstTime = false;
// Create a new instance of the Form2 class
MainFrm MainForm = new MainFrm();
MainForm.Show();
Hide();//This is where Visual Studio is telling me that a "}" is expected
else
{
lblExist.Visible = true;
lblExist.Text = "Folder doesn't exist";
lblExist.ForeColor = Color.Red;
}
}
學習如何格式化代碼是編寫正常工作的代碼的關鍵技能。
private void PathExist()
{
if (Directory.Exists(folderBrowserDialog.SelectedPath + @"\"))
{
lblExist.Visible = false;
Properties.Settings.Default.FirstTime = false;
// Create a new instance of the Form2 class
MainFrm MainForm = new MainFrm();
MainForm.Show();
Hide(); //This is where Visual Studio is telling me that a "}" is expected
}
else
{
lblExist.Visible = true;
lblExist.Text = "Folder doesn't exist";
lblExist.ForeColor = Color.Red;
}
}
請注意如何在 if 語句之后立即添加開頭{
,並在 else 之前添加相應的結尾}
。
現在,您可能會聲稱“但我已經看到 C# 中的代碼,其中大括號是可選的!” 這僅適用於如下所示的單個邏輯行:
if (condition)
ExecuteMethod();
else
ExecuteOtherMethod();
如果條件中的任何代碼塊超過一個“指令”,則必須將該代碼包裝在大括號中。 此外,一些 C# 開發人員會堅持所有代碼都應始終用大括號括起來以避免混淆並作為良好實踐的問題。
你想做什么? 您是否希望僅當目錄存在時才執行 if 和 else 之間的所有語句? 如果是這樣,那么您需要將它們全部放在一個塊中。 並且由於塊有多個語句,因此必須用左括號和右括號指定它。 否則, if 將只包含下一個語句。
private void PathExist()
{
if (Directory.Exists(folderBrowserDialog.SelectedPath + @"\"))
{
lblExist.Visible = false;
Properties.Settings.Default.FirstTime = false;
// Create a new instance of the Form2 class
MainFrm MainForm = new MainFrm();
MainForm.Show();
Hide();
}
else
{
lblExist.Visible = true;
lblExist.Text = "Folder doesn't exist";
lblExist.ForeColor = Color.Red;
}
}
如果你只想要lblExist.Visible = false;
當Directory.Exists
時執行的語句,並且您希望接下來的 4 個語句始終執行,那么您需要解釋else
的用途。 因為它不是 if 子句的一部分。 if
子句,如您lblExist.Visible = false;
,以lblExist.Visible = false;
后的分號lblExist.Visible = false;
您不能在if/else
結構的if
塊和else
塊之間放置旨在始終執行的其他代碼。 這就是產生錯誤的原因。
如果在 IF 語句后不包含 {},則只有 IF 條件下的一個語句會被視為在 if 塊中。 並且您的 else 塊沒有與之關聯的 If 條件。
編譯器認為它是
private void PathExist()
{
if (Directory.Exists(folderBrowserDialog.SelectedPath + @"\"))
{
lblExist.Visible = false;
}
Properties.Settings.Default.FirstTime = false;
// Create a new instance of the Form2 class
MainFrm MainForm = new MainFrm();
MainForm.Show();
Hide();
else
{
lblExist.Visible = true;
lblExist.Text = "Folder doesn't exist";
lblExist.ForeColor = Color.Red;
}
}
否則塊無效。 這可以解決如下。
private void PathExist()
{
if (Directory.Exists(folderBrowserDialog.SelectedPath + @"\"))
{//Answer
lblExist.Visible = false;
Properties.Settings.Default.FirstTime = false;
// Create a new instance of the Form2 class
MainFrm MainForm = new MainFrm();
MainForm.Show();
Hide();
}//Answer
else
{
lblExist.Visible = true;
lblExist.Text = "Folder doesn't exist";
lblExist.ForeColor = Color.Red;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.