当代码中有finally块时,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace ConsoleApplication13
{
enum Orientation : byte
{
North = 1,
South = 2,
East = 3,
West = 4
}
class Program
{
static void Main(string[] args)
{
Orientation myDirection;
for (byte myByte = 2; myByte < 10; myByte++)
{
try
{
myDirection = checked((Orientation)myByte);
if ((myDirection < Orientation.North) || (myDirection > Orientation.West))
{
throw new ArgumentOutOfRangeException("Value must between 1 and 4");
}
}
catch (ArgumentOutOfRangeException e)
{
WriteLine(e.Message);
WriteLine("myDirection is assigned by default value, North");
myDirection = Orientation.North;
}
finally
{
WriteLine($" mydirection = {myDirection}");
}
ReadKey();
}
}
}
}
这时 WriteLine($" mydirection = {myDirection}");显示myDirection未赋值。
但是当将
finally
{
WriteLine($" mydirection = {myDirection}");
}
改为只剩下
WriteLine($" mydirection = {myDirection}");
时,就可以正常运行了。
不清楚这个checked((Orientation)myByte)为什么在有finally块的时候没有成功赋值