用Json.net往返F#歧视工会的问题 [英] Problems roundtripping F# discriminated unions with Json.net
问题描述
我在F#中具有以下枚举
I have the following enum in F#
type MyEnum =
| Value1
| Value2
| Value3
这是代码编译时编译器生成的内容
This is what the compiler generates when the code compiles
[Serializable]
[DebuggerDisplay("{__DebugDisplay(),nq}")]
public class MyEnum : IEquatable<MyEnum>, IStructuralEquatable, IComparable<MyEnum>, IComparable, IStructuralComparable
{
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[DebuggerNonUserCode]
public bool IsValue1 { get; }
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[DebuggerNonUserCode]
public bool IsValue2 { get; }
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[DebuggerNonUserCode]
public bool IsValue3 { get; }
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[DebuggerNonUserCode]
public int Tag { get; }
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[DebuggerNonUserCode]
public static MyEnum Value1 { get; }
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[DebuggerNonUserCode]
public static MyEnum Value2 { get; }
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[DebuggerNonUserCode]
public static MyEnum Value3 { get; }
[CompilerGenerated]
public override sealed int CompareTo(MyEnum obj);
[CompilerGenerated]
public override sealed int CompareTo(object obj);
[CompilerGenerated]
public override sealed int CompareTo(object obj, IComparer comp);
[CompilerGenerated]
public override sealed bool Equals(MyEnum obj);
[CompilerGenerated]
public override sealed bool Equals(object obj);
[CompilerGenerated]
public override sealed bool Equals(object obj, IEqualityComparer comp);
[CompilerGenerated]
public override sealed int GetHashCode();
[CompilerGenerated]
public override sealed int GetHashCode(IEqualityComparer comp);
public static class Tags
{
public const int Value1 = 0;
public const int Value2 = 1;
public const int Value3 = 2;
}
}
问题
当上述枚举类型用于序列化时,该序列化要求每个属性的非静态set
进行反序列化时,它将失败.实际上,我已经在RavenDB
和Json.Net
序列化中使用了它,并且得到了以下内容
Problem
When the above enum type is used for serialization which requires non-static set
for each property for deserialization, it fails. In fact I have used it with RavenDB
and Json.Net
serialization and I get the following
myenummember = {}
如何有效地将F#枚举类型与序列化程序一起使用?
How do I effectively make use of F# enum types with serializers ?
推荐答案
尝试使用可序列化"(Serializable)属性标记类型.另外,为模式标识符提供分配可能有助于编译器推断它是枚举,而不是求和类型可能会有所帮助.
Try marking the type with the "Serializable" attribute. Also providing assignment for the pattern identifiers might help the compiler infer that it is a enum and not a sum type might help.
[<Serializable>]
type x =
ABC = 1
| ABE = 2
这篇关于用Json.net往返F#歧视工会的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!