C#的TimeZoneInfo系列化 [英] c# TimeZoneInfo serialization

查看:209
本文介绍了C#的TimeZoneInfo系列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是有一点问题与序列化的TimeZoneInfo对象。我试图用的TimeZoneInfo变量数据合同WCF服务,但系列化是失败。所以我写了这一小段代码来测试序列化。这里有一个我做的:

I'm have a bit of a problem with serializing TimeZoneInfo object. I was trying to use TimeZoneInfo variable in data contract for WCF service but the serialization was failing. So i wrote this little piece of code to test the serialization. Here's a what i do:

        var fileName = "tmp.xml";
        var tz = TimeZoneInfo.Local;
        var dataSer = new DataContractSerializer(typeof(TimeZoneInfo));

        try
        {
            using (var xml = new FileStream(fileName, FileMode.Create))
            {
                dataSer.WriteObject(xml, tz);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

现在,当我调用writeObject方法抛出异常:

Now, when i call WriteObject method it throws an exception:

键入System.TimeZoneInfo + AdjustmentRule []'数据合同名称'ArrayOfTimeZoneInfo.AdjustmentRule:HTTP://schemas.datacontract.org/2004/07 /不期望系统。考虑使用DataContractResolver或者添加静态已知到已知类型的列表中的任何类型的不 - 例如,通过使用KnownTypeAttribute属性或通过将其添加到已知类型传递给DataContractSerializer列表

Type 'System.TimeZoneInfo+AdjustmentRule[]' with data contract name 'ArrayOfTimeZoneInfo.AdjustmentRule:http://schemas.datacontract.org/2004/07/System' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

如果我尝试添加
[KnownType(typeof运算(System.TimeZoneInfo.AdjustmentRule []))]对类我得到了同样的错误。如果我这一行添加到我的数据接口的合同,我得到编译错误:

If i attempt to add [KnownType(typeof(System.TimeZoneInfo.AdjustmentRule[]))] to the class i get the same error. And if i add this line to my data contract interface i get compile error:

错误1'System.TimeZoneInfo.AdjustmentRule是由于无法访问其保护级别

Error 1 'System.TimeZoneInfo.AdjustmentRule' is inaccessible due to its protection level

和根据文档的TimeZoneInfo类实现ISerializable的,所以应该默认序列化。

And according to the documentation TimeZoneInfo class implements ISerializable so it should serialize by default.

谁能告诉我什么,我做错了什么?我将不胜感激任何帮助。

Can anyone tell me what i'm doing wrong here? I would appreciate any help.

感谢。

推荐答案

我不知道为什么它不只是简单的序列,但你认为只是序列化的 ID ?这很可能是相当更加高效 - 更简单! - 比内所有序列的信息,应该罚款,只要这两个系统都具有时区

I'm not sure why it doesn't just serialize simply, but have you considered just serializing the ID? That's likely to be rather more efficient - and simpler! - than serializing all the information inside, and should be fine so long as both systems have that time zone.

编辑:请注意,这不会使用自定义时区工作,为此,你应该看看 ToSerializedString 其他地方注明。

Note that this won't work with custom time zones, for which you should look at ToSerializedString as noted elsewhere.

这篇关于C#的TimeZoneInfo系列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆