c# (ENUM)枚举组合类型的谷歌序列化Protobuf

时间:2024-03-27 15:33:20

c# (ENUM)枚举组合类型的谷歌序列化Protobuf,必须在序列化/反序列化时加上下面:

RuntimeTypeModel.Default[typeof(Alarm)].EnumPassthru = true;

[ProtoContract]
    class LbsItem
    {
        [ProtoMember(1)]
        public Alarm alarm
        {
            get; set;
        }
    }
   
    public enum Alarm : byte
    {
        无报警,
        碰撞 = 1 << 0,
        振动 = 1 << 1,
        超速 = 1 << 2,
    }

 

    public class ProtobufHelper
    {
        static ProtobufHelper()
        {
            RuntimeTypeModel.Default[typeof(Alarm)].EnumPassthru = true;
        }
        /// <summary>
        /// 序列化
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="t">对象</param>
        /// <returns>序列化后的字符串</returns>
        public static string Serialize<T>(T t)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                Serializer.Serialize<T>(ms, t);
                return Convert.ToBase64String(ms.ToArray());
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="content">字符串</param>
        /// <returns>反序列化后的对象</returns>
        public static T DeSerialize<T>(string content)
        {
            using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(content)))
            {
                T t = Serializer.Deserialize<T>(ms);
                return t;
            }
        }
    }

 

示例:

Alarm alarm = Alarm.振动 | Alarm.碰撞;

            LbsItem item = new Demo.LbsItem();
            item.alarm = alarm;

            var serValue= ProtobufHelper.Serialize<LbsItem>(item);
            var _item = ProtobufHelper.DeSerialize<LbsItem>(serValue);