简单的十六进制值转换为Enum类型值问题
我已经和这个小问题斗争了一晚上了,但我无法解决。我想要的只是拥有一些具有十六进制值的枚举元素并将值转换为枚举,但 .NET 不知何故认为我的枚举不合法。
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);
}
}
}
出了什么问题,我应该如何解决?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该使用
并且
command
应该定义为通常,看起来您不需要包装类
CommandEnum
,您应该只定义enum Command
You should use
and
command
should be defined asGenerally, it looks like you do not need a wrapper class
CommandEnum
, you should just defineenum Command
CommandEnum
不是枚举,它是一个类!您已将枚举Command
定义为“内部”枚举,因此以下内容应该有效:CommandEnum
is not an enum, it is a class! You have defined your enumCommand
as an 'inner' enum, so the following should work:您向其传递包含枚举
CommandEnum
的类的名称,而不是枚举CommandEnum.Command
的名称。以下内容应该适合您:此外,您使用的语法相当复杂,您可以直接转换:
You are passing it the name of the class containing your enum
CommandEnum
, instead of the name of your enum,CommandEnum.Command
. The following should work for you:Also, the syntax that you are using is fairly convoluted, you can just cast instead:
尝试
或更好,
在您的原始代码中您使用了所有错误的类型。您的枚举类型是 CommandEnum 类的公共嵌套类型(并且确实没有充分的理由这样做)。尝试摆脱
CommandEnum
类并仅使用Command
枚举。Try
or better,
In your original code you are using all the wrong types. Your enumeration type is a public nested type for
CommandEnum
class (and there is really no good reason to do something like that). Try to get rid ofCommandEnum
class and justuse theCommand
enum.由于您的枚举是 typeof(byte) 只是将其强制转换,因此无需执行任何其他操作
CommandEnum.Command val= (CommandEnum.Command)receiveByte;
PS 您不能有 0x00 标志。
Since your enum is typeof(byte) just cast it, no need to do anything else
CommandEnum.Command val= (CommandEnum.Command)receiveByte;
P.S. You can't have a 0x00 flag.