【发布时间】:2015-02-10 21:43:55
【问题描述】:
去检查我一直在做的这个程序,我似乎又回到了另一条路,错误说;在控制离开当前方法之前,必须分配 out 参数“checkedIfInsured”。
如有必要,我可以粘贴其余代码,但在我看来,它看起来不错。
static void GetData(out int patientsID, out string patientsName, out int patientsAge, out decimal patientsAmount, object o, out char checkedIfInsured)
{
string inString;
int count = 3;
char test;
Console.Write("Please enter Patients ID number>> ");
inString = Console.ReadLine();
int.TryParse(inString, out patientsID);
Console.Write("Please Enter Name for " + "Patient {0} >> ", patientsID);
patientsName = Console.ReadLine();
Console.Write("Please Enter The Age For " + "Patient {0}>> ", patientsName);
inString = Console.ReadLine();
int.TryParse(inString, out patientsAge);
Console.Write("Please Enter The Amount Due For " + "Patient {0}>> ", patientsID);
inString = Console.ReadLine();
decimal.TryParse(inString, out patientsAmount);
Console.WriteLine("-----------------------------------");
if (o is InsuredPatient)
{
Console.WriteLine(" Enter the name of the Patients Insurance Company Code>>");
for (int x = 0; x < count; ++x)
Console.WriteLine("{0,-3} = {1,5}", InsuredPatient.InsurerCharacter[x], InsuredPatient.InsurerName[x]);
Console.WriteLine(" Enter talent code >> ");
test = Console.ReadKey().KeyChar;
for (int i = 0; i < InsuredPatient.InsurerCharacter[i]; ++i)
if (test == InsuredPatient.InsurerCharacter[i])
{
checkedIfInsured = InsuredPatient.InsurerCharacter[i];
}
}
}
【问题讨论】:
-
该错误的意思正是它所说的。如果循环中的
if子句不为真(或者如果InsuredPatient.InsurerCharacter[i]为<= 0,o is InsuredPatient为假),则永远不会分配checkIfInsured。 -
这个函数是一个主要的候选函数,可以重构为
static GetDataResults GetData(object o),并以单个自定义返回类型返回所有这些 out 语句。除非您在非托管代码中 P/Invoking,否则很少会同时执行具有void返回类型和out参数的函数是一个很好的设计选择。 -
顺便说一句,使用这么多
out参数似乎是非常糟糕的设计。只需返回一个包含相关值的对象。
标签: c#