似乎這個特定的錯誤已經被解決了很多次,但是我的代碼片段有一些不同之處,因爲它永遠不會導致「未分配」錯誤。在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