我觉得这可能是一个有点愚蠢的问题,但作为C#初学者,我已经尝试了目前所知道的一切。有什么方法可以将一个值返回到我已经设置为在其他地方使用的值中吗?还是我把这整件事搞得太复杂了?每次我试图用花括号内的一个变量来设置已经存在的变量时,我都会得到一个错误。我在下面使用的代码。
static double GetAmount()
{
double amount;
try
{
Console.WriteLine("Enter in the amount for the transaction: ");
double amount1 = Convert.ToDouble(Console.ReadLine());
return amount1;
}
catch (Exception ex)
{
bool f = true;
Console.WriteLine(ex.Message);
while (f == true)
try
{
Console.WriteLine("Enter the total in a proper format, no letters or spaces please. ");
double amount1 = Convert.ToDouble(Console.ReadLine());
f = false;
return amount1;
}
catch (Exception ex2)
{
Console.WriteLine(ex2.Message);
Console.WriteLine("Please try again.");
}
}
finally
{
return amount;
}
return amount;
}
您会得到两个编译错误和一个警告。要理解它们,您必须知道finally块总是在从try-or-catch块返回之前执行的。即return amount1;
将执行最后块return amount;
中的语句。但是只能执行一个返回语句。因此,您得到的信息是:
CS0157控件不能离开finally子句的主体
和
CS0165使用未分配的本地变量"金额">
因为变量已声明,但在调用return时尚未赋值。
此外,你会收到警告
CS0162检测到无法访问的代码
在最后一行代码中,因为该方法要么被前面的一个返回语句留下,要么永远留在while循环中。因此,最后一条返回语句永远无法执行。
布尔标志f
是冗余的。在return语句之前将其设置为true
没有意义,因为该方法在return语句处退出。这将同时终止while循环。如果您想退出循环而不返回,可以调用break;
。
使用try-catch的简化版本:
static double GetAmount()
{
Console.Write("Enter in the amount for the transaction: ");
while (true) {
try {
double amount = Convert.ToDouble(Console.ReadLine());
return amount;
} catch (Exception ex) {
Console.WriteLine(ex.Message);
Console.Write("Enter the total in a proper format, no letters or spaces please: ");
}
}
}
语句while (true)
引入了一个无休止的循环。无尽,除非它是由return
、break
或未处理的异常(或不受欢迎的goto命令(留下的。
一个更好的选择是使用不抛出异常的TryParse
方法
static double GetAmount()
{
Console.Write("Enter the amount for the transaction: ");
while (true) {
if (Double.TryParse(Console.ReadLine(), out double amount)) {
return amount;
}
Console.Write("Enter the total in a proper format: ");
}
}
这个版本与你的功能相同,安全,体积小3倍,阅读起来更容易。
另请参阅:try finally(C#参考(
static double GetAmount()
{
double amount = 0;
try
{
Console.WriteLine("Enter in the amount for the transaction: ");
amount = Convert.ToDouble(Console.ReadLine());
}
catch (Exception ex)
{
bool f = true;
Console.WriteLine(ex.Message);
while (f)
try
{
Console.WriteLine("Enter the total in a proper format, no letters or spaces please. ");
amount = Convert.ToDouble(Console.ReadLine());
f = false;
}
catch (Exception ex2)
{
Console.WriteLine(ex2.Message);
Console.WriteLine("Please try again.");
}
}
return amount;
}