【发布时间】:2019-10-08 17:22:36
【问题描述】:
我正在尝试使用 JSon.NET 序列化一个不可变结构,但我不知道该怎么做。序列化的结果是一个空的 json {}。我更喜欢使用 JsonNET 而不是像BinaryFormatter。
结构
[Serializable]
public struct Settings : IEquatable<Settings> {
private readonly (
TimeSpan from,
TimeSpan until,
TimeSpan repeatInterval,
TimeSpan popupInterval,
string notes
) _value;
[JsonIgnore]
public TimeSpan From => _value.from;
[JsonIgnore]
public TimeSpan Until => _value.until;
[JsonIgnore]
public TimeSpan Repeat => _value.repeatInterval;
[JsonIgnore]
public TimeSpan PopUpInterval => _value.popupInterval;
[JsonIgnore]
public string Notes => _value.notes;
public Settings(
TimeSpan from,
TimeSpan until,
TimeSpan repeatInterval,
TimeSpan popUpInterval,
string notes
) => _value = (
from,
until,
repeatInterval,
popUpInterval,
notes
);
public bool Equals(Settings other) => _value == other._value;
public override bool Equals(object obj) => obj is Settings other && this.Equals(other);
public override int GetHashCode() => _value.GetHashCode();
public override string ToString() => _value.ToString();
public static bool operator ==(Settings a, Settings b) => a.Equals(b);
public static bool operator !=(Settings a, Settings b) => !(a == b);
}
计划
static void Main(string[] args) {
Settings settings = new Settings(new TimeSpan(0),
new TimeSpan(0,1,1),
new TimeSpan(1,2,3),
new TimeSpan(2,4,3),
"adisor");
var obj = JsonConvert.SerializeObject(settings);
var newone = JsonConvert.DeserializeObject<Settings>(obj);
}
【问题讨论】:
标签: serialization struct .net-core json.net immutability