首页 > 解决方案 > 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?

标签: c#enumsprotobuf-net

解决方案


感谢您的评论!我根据我读过的其他一些帖子找到了一种方法。

回应第一条评论,我无法在基类上定义特定的枚举,因为我事先不知道,每个派生类都有自己的枚举。所以我想出了一个不同的方法。

首先,我添加了一个功能:

在基地:

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; }

我真的不知道是否是最好的方法,但它有效!


推荐阅读