我在f#
中有以下枚举 type MyEnum =
| Value1
| Value2
| Value3
这是当代码编译
时编译器生成的结果 [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
序列化,并得到以下
myenummember = {}
如何有效地利用f#枚举类型与序列化器
您可以提供JsonConverter实例,知道如何将此转换回来&div。
虽然Json.net 6.0(.1?)提供了对f# DUs的支持,但仍有许多缺点(我在@John Palmer的链接中的回答和评论中提到了其中一些缺点)。
FsUno。Prod合并了一个Serialization.fs
(由jsamrsammie Chassaing编写),它解决了这些问题和更多问题[使用@Ayende Rahien提到的技术]。
(在我的分叉中,funddomain包含了一些进一步的扩展)这里。(这些变化可能最终会回到FsUno。
尝试用"Serializable"属性标记类型。此外,为模式标识符提供赋值可能有助于编译器推断它是enum类型而不是sum类型。
[<Serializable>]
type x =
ABC = 1
| ABE = 2