假设我有自定义枚举
public sealed class Shape
{
// enum values
public static readonly Shape Circle = new Shape(100, "Circle");
public static readonly Shape Square = new Shape(200, "Square");
public static readonly Shape Rectangle = new Shape(300, "Rectangle");
// enum value properties
public readonly short Number;
public readonly string Name;
// private constructor
private Shape(short number, string name)
{
Number = number;
Name = name;
}
}
我希望以这种方式支持newtonsoft JSON.Net序列化:
Shape.Circle
已序列化为100
100
被反序列化为Shape.Circle
"Circle"
也被反序列化为Shape.Circle
我可以为类中的此Enum对象的de / -serialization设置逻辑,例如从int
和string
设置隐式运算符转换或使用一些特殊的JSON.Net属性,属性?我希望Enum对象中包含所有逻辑,因此用户只需将类型标记为Shape
,就不需要设置自定义convertors
等。