c# - protobuf-net:无法使用 System.Enum 属性进行序列化
问题描述
我会试着用一个例子来解释我想要做什么
[ProtoContract]
[ProtoInclude(101, typeof(SomeDerived))]
[ProtoInclude(102, typeof(AnotherDerived))]
public abstract class Base
{
protected Base() {}
public Base(double doubleProp, Enum enumProp)
{
DoubleProp = doubleProp;
EnumProp = enumProp;
}
[ProtoMember(1)]
public double DoubleProp { get; }
[ProtoMember(2)]
public Enum EnumProp { get; }
//More stuff
}
public enum SomeDerivedEnum
{
//Some Enum Values
}
public enum AnotherDerivedEnum
{
//Another Enum Values
}
public class SomeDerived : Base
{
private SomeDerived () : base() {}
public SomeDerived (double doubleProp, SomeDerivedEnum someEnum)
: base(doubleProp, someEnum)
{
}
//More Stuff
}
public class AnotherDerived : Base
{
private AnotherDerived () : base() {}
public AnotherDerived (double doubleProp, AnotherDerivedEnum anotherEnum)
: base(doubleProp, anotherEnum)
{
}
//More Stuff
}
当我尝试序列化时,出现以下错误
System.InvalidOperationException:没有为类型定义序列化程序:System.Enum
有一种方法可以将任何 System.Enum 值转换为 int 并返回 protobuf?
解决方案
感谢您的评论!我根据我读过的其他一些帖子找到了一种方法。
回应第一条评论,我无法在基类上定义特定的枚举,因为我事先不知道,每个派生类都有自己的枚举。所以我想出了一个不同的方法。
首先,我添加了一个功能:
在基地:
protected virtual Type GetEnumtype() => typeof(Enum)
在 SomeDerived 上(例如)
protected override Type GetEnumType() => typeof(SomeDeviredEnum);
然后我创建了一个中间私有 int 属性来序列化我的枚举并使用覆盖函数进行转换。
[ProtoMember(2)]
private int intPvtProp
{
get => System.Convert.ToInt32(EnumProp);
set => EnumProp = (Enum)Enum.ToObject(GetEnumType(), value);
}
public Enum EnumProp { get; }
我真的不知道是否是最好的方法,但它有效!
推荐阅读
- hibernate - 如何在休眠中仅从表和连接表中的多对多关系中获取数据
- javascript - 如何获取文档上的所有嵌套 iframe?
- c# - 从数据库中填充自定义 TreeView,其中父母按字母缩进
- java - 使用 AppCompat 主题后如何删除按钮中多余的白色背景?
- css - 如何使列占用剩余空间
- sql-server - 在数据库中的所有表上执行的 SQL 脚本
- r - 在数据框中过滤具有每个 ID 的最大日期的数据
- reactjs - 服务器端 webpack 无法从 node_modules 读取 css 文件
- java - 如何从文件“历史”中读取 Chrome 年表
- angular - 如何从返回 observable 的函数订阅 observable?