我试图弄清楚如何为值创建属性 [NonSerialized]
看看这个:
using System;
using System.Text.Json;
class Test
{
public static bool GoingToBeSerialized = false;
public int PaymentForTheDay { get; set; }
public int NumberOfDays { get; set; }
// i want to disable it if GoingToBeSerialized is true
[System.Text.Json.Serialization.JsonIgnore]
public int TotalPayment;
public bool ShouldSerializeTotalPayment() => GoingToBeSerialized;
}
谢谢。
最佳答案
请注意,[Serialized]
和 [NonSerialized]
(在原始问题中,现已在编辑中删除)对大多数序列化器没有任何作用- 它们仅适用于您没有使用的 BinaryFormatter
。
很有可能简单地使用:
public int TotalPayment {get;set;}
public bool ShouldSerializeTotalPayment() => GoingToBeSerialized;
会做你想做的事;最近添加的 Pastebin 显示您正在使用 Json.NET,这确实应该有效 - conditional serialization is a Json.NET feature using the standard pattern 。另请注意,我将 TotalPayment
设为属性,并删除了 [JsonIgnore]
。
关于c# - 为值设置属性 [NonSerialized],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67667924/