本文介绍了protobuf网连载枚举值为超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#允许指定的任何整数值枚举。



当我尝试序列化(通过protobuf网)与枚举字段对象,它的值超出范围,它抛出异常:无线值映射到枚举PersonLevel



我的枚举PersonLevel没有标记属性



[ProtoContract(ImplicitFields = ImplicitFields.AllFields)]
公共枚举PersonLevel
{
未知= 1
}

[ProtoContract(ImplicitFields = ImplicitFields.AllFields)]
公共类Person
{
...

公共PersonLevel PersonLevel {搞定;组; }


}



VAR毫秒=新的MemoryStream();

变种人=新的Person
{
...
PersonLevel =(PersonLevel)500

};

Serializer.Serialize(MS,人); //没有线值映射到枚举PersonLevel

是否有任何设施,做到这一点不改变?业务对象(可以是任何的protobuf attrubutes)


解决方案

有一对夫妇告诉它简化了规则的途径;作为Ravadre指出, [国旗] 自动禁用验证 - 它会导致 EnumPassthru 变得切换。您也可以手动做到这一点 - 只要它的之前你开始串行/解串:

  RuntimeTypeModel.Default [typeof运算(PersonLevel)EnumPassthru = TRUE。 



里面有说明:

  ///<总结> 
///获取或设置指示枚举应直接视为一个int /短/等,而
///不是强制执行.proto枚举规则的值。这是特别有用的*为* [标志]枚举。
///< /总结>


C# allows to assign any integer value to enum.

When I try to serialize (via protobuf-net) object with enum field which value is out of range, it throws exception: No wire-value is mapped to the enum PersonLevel.

My enum PersonLevel doesn't have Flags attribute.

[ProtoContract(ImplicitFields = ImplicitFields.AllFields)]
public enum PersonLevel
{
  Unknown = 1
}

[ProtoContract(ImplicitFields = ImplicitFields.AllFields)]
public class Person
{
  ...

  public PersonLevel PersonLevel { get; set; }

  ...
}
var ms = new MemoryStream();

var person = new Person
{
  ...
  PersonLevel = (PersonLevel) 500
  ...
};

Serializer.Serialize(ms, person); //No wire-value is mapped to the enum PersonLevel

Is there any facilities to do it without changing business objects (maybe any protobuf attrubutes)?

解决方案

There are a couple of ways of telling it to simplify the rules; as Ravadre notes, [Flags] automatically disables validation - it causes EnumPassthru to become toggled. You can also do this manually - as long as it is before you start serializing / deserializing:

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

which has the description:

/// <summary>
/// Gets or sets a value indicating that an enum should be treated directly as an int/short/etc, rather
/// than enforcing .proto enum rules. This is useful *in particular* for [Flags] enums.
/// </summary>

这篇关于protobuf网连载枚举值为超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 13:42