我的代码出现了以下错误
error Use of unassigned local variable (switch) in C# for strFavoriteColor
我的代码:
private void lstData_SelectedIndexChanged(object sender, EventArgs e)
{
string strName;
string strFavoriteColor;
strName = lstData.Items[lstData.SelectedIndex].ToString();
switch (strName)
{
case "Amir":
strFavoriteColor = "Abi";
break;
case "Mahdi":
strFavoriteColor = "Sabz";
break;
case "Meisam":
strFavoriteColor = "Siah";
break;
case "Amin":
strFavoriteColor = "zard";
break;
case "Reza":
strFavoriteColor = "banafsh";
break;
}
MessageBox.Show(strName + "'s favorite color is " + strFavoriteColor, "Select Demo");
可能是什么问题?
答案 0 :(得分:2)
strFavoriteColor
的表达式中使用它时, MessageBox.Show()
可能尚未初始化。
您可以使用switch语句中的默认大小写来解决这个问题。
switch (strName)
{
case "Amir":
strFavoriteColor = "Abi";
break;
case "Mahdi":
strFavoriteColor = "Sabz";
break;
....
default:
strFavoriteColor = "<unknown>";
break;
}
MessageBox.Show(...); // now strFavoriteColor has definitely been initialized
答案 1 :(得分:1)
而不是
string strFavoriteColor;
写
string strFavoriteColor = "";
你没有初始化它,你的交换机声明可能没有任何匹配。