gpt4 book ai didi

c# - 在项目设置中保存 DateTimeOffset 设置时丢失精度

转载 作者:行者123 更新时间:2023-11-30 12:30:56 26 4
gpt4 key购买 nike

当我在项目设置中保存 DateTimeOffest 时,我失去了一些精度: Losing precision on DateTimeOffset serialization

第一个变量是序列化前的原始值。二是反序列化后的值。

事实上我的变量在配置文件中是这样序列化的:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<userSettings>
<MyApp.Properties.Settings>
[...]
<setting name="LatestCheckTimestamp" serializeAs="String">
<value>02/22/2013 14:39:06 +00:00</value>
</setting>
[...]
</MyApp.Properties.Settings>
</userSettings>
</configuration>

有没有办法指定一些序列化参数来提高精度?

我知道我可以使用一些解决方法,例如通过存储刻度和偏移值或类似的东西,但我想知道是否没有更好的方法。

编辑:更多信息:我正在使用标准的 Visual Studio 项目设置来存储我的值:

MyApp.Settings.Default.LatestCheckTimestamp = initialLatestCheckTimestamp;
MyApp.Settings.Default.Save();

MyApp.Settings 是您在项目属性页面中编辑设置时由 Visual Studio 生成的类。

编辑 2:解决方案:

根据 Matt Johnson 的回答,这就是我所做的:

  1. 将设置从 LatestCheckTimestamp 重命名为 LatestCheckTimestampString不在我的代码中
  2. 在独立文件中添加以下 Wrapper 以完成部分类 Settings :

.

public DateTimeOffset LatestCheckTimestamp
{
get { return DateTimeOffset.Parse(LatestCheckTimestampString); }
set { LatestCheckTimestampString = value.ToString("o"); }
}

新的配置文件现在看起来像:

<configuration>
<userSettings>
<MyApp.Properties.Settings>
[...]
<setting name="LatestCheckTimestampString" serializeAs="String">
<value>2013-02-22T16:54:04.3647473+00:00</value>
</setting>
</MyApp.Properties.Settings>
</userSettings>
</configuration>

...我的代码仍然是

MyApp.Settings.Default.LatestCheckTimestamp = initialLatestCheckTimestamp;
MyApp.Settings.Default.Save();

最佳答案

序列化 DateTimeOffset 的最可靠方法是使用 RoundTrip pattern ,这是用 "o" 标准序列化字符串指定的。

这使用了 ISO8601标准,它与其他系统、语言、框架等具有高度互操作性。您的值将如下所示:2013-02-22T14:39:06.0000000+00:00

.Net 将使用这种格式将小数秒存储为 7 位小数。

如果您可以展示一些有关如何存储和检索应用设置的代码,我可以告诉您在何处指定格式字符串。在大多数情况下,它只是 .ToString("o")

关于c# - 在项目设置中保存 DateTimeOffset 设置时丢失精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15027343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com