[英]How to load values via System.Text.Json from a file and store them readonly?
我想通過 System.Text.Json 從 JSON 文件加載設置。 這些設置在加載后都應該是只讀的。
到目前為止我的代碼:
string jsonString = File.ReadAllText(filename);
Settings s = JsonSerializer.Deserialize<Settings>(jsonString);
和設置類:
public class Settings
{
public decimal A { get; set; }
public int B { get; set; }
public double C { get; set; }
public double D { get; set; }
}
問題:值是可編輯的並使用private set;
不起作用,因為 JsonSerializer 需要能夠訪問 setter。
為序列化程序創建一個帶有公共set
的基類,然后在不允許對其進行變異的派生類中覆蓋它們。
我建議您更改設計並創建一個具有所有可變屬性的基類,這將成為任何反序列化操作的目標(因為可變屬性與反序列化配合得很好)。 然后消費者將通過從該基類中隱蔽/復制/反射它來獲取不可變實例。
var bse = JsonConvert.DeserializeObject<MutablePropertyStore>("{ 'PropertyB' : true }");
Console.WriteLine("Base: " + bse.ToString());
var derived = new ImmutablePropertyStore(bse);
Console.WriteLine("Derived: " + derived.ToString());
結果
Base: Property A is 'False' and Property B is 'True'.
Derived: Property A is 'False' and Property B is 'True'.
代碼
public sealed class ImmutablePropertyStore : MutablePropertyStore
{
public new bool PropertyA { get; private set; }
public new bool PropertyB { get; private set; }
public ImmutablePropertyStore() { }
public ImmutablePropertyStore(MutablePropertyStore ms)
{
PropertyA = ms.PropertyA;
PropertyB = ms.PropertyB;
}
public ImmutablePropertyStore(bool propertyA = true, bool propertyB = false)
{
PropertyA = propertyA;
PropertyB = propertyB;
}
public override string ToString()
=> $"Property A is '{PropertyA}' and Property B is '{PropertyB}'.";
}
public class MutablePropertyStore
{
public virtual bool PropertyA { get; set;}
public virtual bool PropertyB { get; set;}
// Set all defaults here
public MutablePropertyStore() { }
public override string ToString()
=> $"Property A is '{PropertyA}' and Property B is '{PropertyB}'.";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.