下面的代码为什么没有进入catch块
enum Orientation : byte
{
north = 1,
south = 2,
east = 3,
west = 4
}
class Program
{
static void Main(string[] args)
{
byte[] myByte = { 1, 3, 9, 4 };
Orientation myDirection;
try
{
for (int i = 0; i < myByte.Length; i++)
{
byte temp = myByte[i];
checked
{
myDirection = (Orientation)temp;
}
Console.WriteLine(myDirection.ToString());
}
}
catch (Exception e)
{
Console.WriteLine("无法正常转换" + e.ToString());
}
Console.ReadLine();
} }
enum Orientation : byte
{
north = 1,
south = 2,
east = 3,
west = 4
}
class Program
{
static void Main(string[] args)
{
byte[] myByte = { 1, 3, 9, 4 };
Orientation myDirection;
try
{
for (int i = 0; i < myByte.Length; i++)
{
byte temp = myByte[i];
checked
{
myDirection = (Orientation)temp;
}
Console.WriteLine(myDirection.ToString());
}
}
catch (Exception e)
{
Console.WriteLine("无法正常转换" + e.ToString());
}
Console.ReadLine();
} }
{
/// <summary>
/// 注册
/// </summary>
Register = 1,
/// <summary>
/// 登陆
/// </summary>
Login = 2,
/// <summary>
/// 添加好友
/// </summary>
AddFirend = 3,
/// <summary>
/// QQUser信息
/// </summary>
QQUser = 4,
/// <summary>
/// 文字消息
/// </summary>
Message = 5,
/// <summary>
/// 客户端和服务器端之间断开连接
/// </summary>
Disconn = 6,
/// <summary>
/// 客户端退出登录
/// </summary>
Logout = 7
}
void _SocketClient_TCPDataArrival(TCPDataEventArgs args)
{
switch (args.Code.PackageHead)
{
case EPackageHead.Register:
this.Register(args);
break;
case EPackageHead.Login:
this.Login(args);
break;
case EPackageHead.AddFirend:
this.AddFirent(args);
break;
case EPackageHead.QQUser:
this.QQUser(args);
break;
case EPackageHead.Message:
this.Message(args);
break;
}
}
看里面这样一句话:可以将任意整数值赋给 meetingDay。 例如,代码行 meetingDay = (Days) 42 不会产生错误。 但也不应该这样做,因为默认约定的是枚举变量只容纳枚举定义的值之一。 将任意值赋给枚举类型的变量很有可能会导致错误。
所以可以互相转化.要判定一个值,是否被枚举包含可以这样:
if (Enum.IsDefined(typeof(Orientation), temp))
当byte都枚举不能转换为对应的枚举值时,还返回byte本身