【发布时间】:2021-09-21 18:06:25
【问题描述】:
我会试着用一个例子来解释我想要做什么
[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?
【问题讨论】:
-
Enum类型是所有枚举类型的基本类型,但它本身不是枚举类型。并非所有枚举类型都由int支持——这是默认设置,但拥有MyEnum : long会产生一个可能无法序列化为int的枚举类型。因为枚举值的实际托管类型不是枚举值的一部分,所以如果它只有Enum,protobuf 就不可能将任意值反序列化为“正确的”枚举类型。总之,如果要int序列化,使用int;稍后根据需要转换为枚举(例如,通过单独的属性)。 -
正如@Jeroen 所说:使用特定的枚举类型,而不是基本类型
标签: c# enums protobuf-net