爲什麼double會被序列化爲NaN

提問

爲什麼double會被序列化爲NaN

回答

世界上存在Double.NaN這個東西,他被序列化就會成爲NaN

example

// See https://aka.ms/new-console-template for more information

using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

Console.WriteLine("Hello, World!");

var isValueValid = double.TryParse(null, NumberStyles.Any, CultureInfo.InvariantCulture, out var tagValue);
Console.WriteLine($"isValueValid:{isValueValid} tagValue:{tagValue}");

var v = new Example()
{
    Name = "12",
    Val = Double.NaN
};
Console.WriteLine(JsonConvert.SerializeObject(v));

Console.WriteLine(Double.IsNaN(v.Val.Value));

public class Example
{
    public string? Name { get; init; }
    
    public double? Val { get; set; }
    
}

  • 輸出:
C:/Repos/tryparse/tryparse/tryparse/bin/Debug/net6.0/tryparse.exe 
Hello, World!
isValueValid:False tagValue:0
{"Name":"12","Val":"NaN"}
True

參考

https://learn.microsoft.com/zh-cn/dotnet/api/system.double.nan?view=net-8.0

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章