C# 通过编组IntPtr将字节转换为枚举
我正在尝试将大小为1的字节数组转换为枚举:C# 通过编组IntPtr将字节转换为枚举,c#,C#,我正在尝试将大小为1的字节数组转换为枚举: public enum InformationMessageLevel : byte { Information = 0, Warning = 1, Error = 2, Fatal = 3 } 使用编组: // bytes = byte[1] = 0 // t is typeof(InformationMessageLevel) unsafe { fixed (byte* p = bytes)
public enum InformationMessageLevel : byte
{
Information = 0,
Warning = 1,
Error = 2,
Fatal = 3
}
使用编组:
// bytes = byte[1] = 0
// t is typeof(InformationMessageLevel)
unsafe
{
fixed (byte* p = bytes)
{
var localPtr = p;
return Marshal.PtrToStructure((IntPtr)localPtr, t);
}
}
但我得到了一个错误:
指定的结构必须是可飞行的或具有布局
信息。\r\n参数名称:结构
我将封送处理与IntPtr结合使用的原因是,此方法用于将数据动态取消序列化为不同类型的属性。不使用封送处理的动态解决方案:
byte[] bytes = { 0 };
var t = typeof(InformationMessageLevel);
var result = Enum.ToObject(t, bytes[0]);
Console.WriteLine(result);
输出:
Information
什么是t?InformationMessageLevel结果=InformationMessageLevel字节[0];?改用Marshal.ReadByte。另外,不要使用封送处理对不会离开托管世界的数据进行序列化/反序列化。它不是为此而设计的,它是为在托管和非托管之间封送而设计的。对于纯托管代码,有更好的序列化解决方案—JSON、BitConverter、BinaryFormatter、protobuf。。。不同的技术适用于不同的场景。封送处理几乎从来都不是正确的选择。@DmitryBychenko抱歉,应该在post按钮上慢一点,有理由地更新问题。您需要的是InformationMessageLevel[]消息=新InformationMessageLevelsize。然后使用Marshal.ptrto结构。