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

4
当我在项目设置中保存一个 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>

有没有一种方法可以指定一些序列化参数以增加精度?

我知道可以使用一些解决方法,例如存储Ticks和偏移值之类的内容,但我想知道是否有更好的方法。

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

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

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

编辑2: 解决方案

根据Matt Johnson的答案,我所做的如下:

  1. 将设置从LatestCheckTimestamp重命名为LatestCheckTimestampString,但不是在我的代码中
  2. 添加以下包装器到一个独立文件中,完成部分类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();

你们计划支持多个Windows用户吗?如果是这样,每个用户是否有自己的“上次检查时间”,还是共享在所有用户之间?ApplicationSettingsBase(您的设置类派生自该类)的一个问题是它不允许写入应用程序范围的设置(尽管有解决方法)。 - jerry
@jerry 我的设置是用户范围的。这方面没有问题。谢谢你的关心。 - JYL
1个回答

3
最可靠的序列化 DateTimeOffset 的方法是使用 RoundTrip 模式,该模式使用 "o" 标准序列化字符串进行指定。
这使用了 ISO8601 标准,与其他系统、语言、框架等高度互操作。您的值将如下所示:2013-02-22T14:39:06.0000000+00:00
.Net 将使用此格式存储小数秒到 7 位小数。
如果您可以展示一些存储和检索应用程序设置的代码,我可以向您展示在哪里指定格式字符串。在大多数情况下,只需使用 .ToString("o") 即可。

根据您的回答,我为存储为字符串而不是DateTimeOffset的值创建了一个包装器。请查看我的编辑。谢谢! - JYL
1
那看起来很合理。我深入研究了一下MSDN文档,似乎你无法为应用程序设置指定格式字符串。这很疯狂,特别是因为它与文化有关,他们使用默认格式。 "o"格式更安全。 - Matt Johnson-Pint

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接