I have been fighting with this little problem for a night and I couldn’t figure it out. All I want is have some enum elements with Hex value and convert a value to enum, but .NET somehow don’t think my enum is legal.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class CommandEnum
{
[Flags]
public enum Command : byte
{
CMD_HAND_SHAKE = 0x0,
CMD_SET_MAX_CURRENT = 0x1,
CMD_SET_TEST_SPEED = 0xA
}
}
class Program
{
static void Main(string[] args)
{
CommandEnum command;
byte receiveByte = 0x0A;
// Error: Type provided must be an Enum. Parameter name: enumType:
command = (CommandEnum)Enum.ToObject(typeof(CommandEnum), receiveByte);
}
}
}
What is wrong and how should I fix it?
You should use
and
commandshould be defined asGenerally, it looks like you do not need a wrapper class
CommandEnum, you should just defineenum Command