为什么不同机器上类的序列化结果不同?

时间:2011-09-16 07:31:45

标签: c# xml serialization

我有一个类Header,看起来像

/// <remarks />
[GeneratedCode("xsd", "4.0.30319.1")]
[Serializable]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace = "http://www.schemas.com/IntegrationApplication-instance")]
[XmlRoot(Namespace = "http://www.schemas.com/IntegrationApplication-instance", IsNullable = true)]
public class Header
{
    private string operationField;

    private string requestIdField;

    private DateTime sendDateField;

    private string senderSystemNameField;

    /// <remarks />
    [XmlElement(IsNullable = true)]
    public string Operation
    {
        get
        {
            return operationField;
        }
        set
        {
            operationField = value;
        }
    }

    /// <remarks />
    public string RequestId
    {
        get
        {
            return requestIdField;
        }
        set
        {
            requestIdField = value;
        }
    }

    /// <remarks />
    public DateTime SendDate
    {
        get
        {
            return sendDateField;
        }
        set
        {
            sendDateField = value;
        }
    }

    /// <remarks />
    [XmlElement(IsNullable = true)]
    public string SenderSystemName
    {
        get
        {
            return senderSystemNameField;
        }
        set
        {
            senderSystemNameField = value;
        }
    }
}

当我在我的机器上对其进行序列化时,指定了SendDate,但是当我在另一台机器上运行序列化代码时,我很惊讶SendDate不知何故错过了。我使用的代码是:

var header = new Header()
            {
                Operation = "new ope",
                RequestId = "",
                SendDate = DateTime.Now,
                SenderSystemName = "asd"
            };
var serializer = new XmlSerializer(typeof (Header));
var sb = new StringBuilder();
serializer.Serialize(new StringWriter(sb, CultureInfo.InvariantCulture), header);

为什么这些代码的结果在不同的机器上有所不同?

1 个答案:

答案 0 :(得分:2)

我觉得这是一个文化问题。我没有看到反序列化代码,但可能是这段代码期望日期采用不同的格式。如果此代码未指定culture,则将运行代码运行的机器的区域设置。检查两台机器的区域设置是否相同,特别是日期格式。