似乎这个特定的错误已经解决了很多次,但是我的代码段却有所不同,因为它永远不会导致“未分配”的错误。
该代码来自我正在上学的一个项目。我可以寻求帮助,这是我希望在这里找到的。我不在乎掩盖任何变量或任何不是出于商业目的的变量。
这是编译时的错误:“使用未分配的局部变量'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;
我的代码段有一些不同之处,那就是永远不会导致“未分配”错误
好吧,它显然确实会导致该错误,这就是为什么您问这个问题,不是吗?
即使您知道任何时候都会引发异常,您都将再次循环,编译器也不知道...因此出错。该值未明确分配。当然,您可以先给它一个虚拟值-但就我个人而言,我不喜欢这样做。
您最好将解析代码提取到一个单独的方法中,该方法可能类似于:
static DateTime RequestStartDate()
{
while (true)
{
try
{
// Ask for date and parse it
// ...
return parsedDate;
}
catch (Exception e) // See below...
{
MessageBox.Show("The date entered is not valid");
}
}
}
该方法肯定会DateTime
最终返回一个值,否则将永远循环下去-因此,通过调用该方法分配的任何变量都将被明确分配。
然后可以在您的主要代码中编写:
switch (userType)
{
case "Doctor":
string qualification = Microsoft.VisualBasic.Interaction.InputBox("What is the highest qualification this person has", "Qualification", "", -1, -1);
DateTime dateStarted = RequestStartDate();
string field = Microsoft.VisualBasic.Interaction.InputBox("In which field does this person practice", "Field", "", -1, -1);
CreateDoctor(qualification, dateStarted, field);
break;
顺便说string.Remove
一句,您正在打电话而不理会结果-总是一个坏主意。手动解析日期是不必要的复杂操作DateTime.TryParseExact
。
另外,捕获Exception
通常不是一个好主意-您应该捕获特定的异常...尽管使用DateTime.TryParseExact
时不需要捕获任何东西,因为false
如果无法解析该值,它将返回。
我还建议您至少有一个using
指令,Microsoft.VisualBasic
以便您可以使用:
string qualification = Interaction.InputBox(...);
等等,而不是每次都有很长的线。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句