为值创建属性 [NonSerialized]

问题描述

我想弄清楚如何为一个值创建一个属性 [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;
}

谢谢。

解决方法

请注意,[Serializable][NonSerialized](在原始问题中,现在已在编辑中删除)对大多数序列化程序没有任何作用 - 它们仅适用于 BinaryFormatter ,您没有使用。

很有可能只是使用:

public int TotalPayment {get;set;}
public bool ShouldSerializeTotalPayment() => GoingToBeSerialized;

会做你想做的;最近添加了显示您正在使用 Json.NET 的 pastebin,这确实应该有效 - conditional serialization is a Json.NET feature using the standard pattern。另请注意,我将 TotalPayment 设为 属性,并删除了 [JsonIgnore]

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...