似乎这个特定的错误已经被解决了很多次,但是我的代码片段有一些不同之处,因为它永远不会导致“未分配”错误。在Try Catch中使用未分配的局部变量
此代码来自我为学校所做的一个项目。我被允许寻求帮助,这是我希望在这里找到的。我不在乎掩盖任何变数或任何因为它不是用于商业目的。
这是在编译时错误: “未分配的局部变量的使用‘dateStartedActual’”
switch (userType)
{
case "Doctor":
string qualification = Microsoft.VisualBasic.Interaction.InputBox("What is the highest qualification this person has", "Qualification", "", -1, -1);
while (dateStarted == "")
{
try
{
dateStarted = Microsoft.VisualBasic.Interaction.InputBox("On which date did this person start", "Date Started", "", -1, -1);
int day = Convert.ToInt32(Regex.Match(dateStarted, @"\d{2}").Value);
dateStarted.Remove(0,3);
int month = Convert.ToInt32(Regex.Match(dateStarted, @"\d{2}").Value);
dateStarted.Remove(0,3);
int year = Convert.ToInt32(Regex.Match(dateStarted, @"\d{4}").Value);
dateStartedActual = new DateTime(day, month, year);
}
catch (Exception ex)
{
MessageBox.Show("The date entered is not valid");
dateStarted = "";
}
}
string field = Microsoft.VisualBasic.Interaction.InputBox("In which field does this person practice", "Field", "", -1, -1);
CreateDoctor(qualification, dateStartedActual, field);
break;
它是在while循环中检查dateStarted ==为“”,它将被设置为catch中的值。所以同时将再次从顶部启动try catch块。如果日期不正确,它将永远不会到达CreateDoctor – Aernor
@Anor:是的,意识到并编辑。 –
谢谢,我会尝试。感谢您的及时回复 – Aernor