CSharp / DotNet:序列化,泛型和基类

时间:2009-08-27 08:28:51

标签: .net generics serialization inheritance

有人可以告诉我为什么这个课要求[XmlInclude(typeof(AutoHedgerBaseDataObject))]正确反序列化?我不清楚。

[Serializable]
[XmlInclude(typeof(AutoHedgerBaseDataObject))]
public abstract class AutoHedgerCommandMessage 
{
    #region Variables

    private string myUpdatedBy;
    private string myUpdatedTime;

    #endregion

    #region Constructors

    public AutoHedgerCommandMessage(string name)           
    {
        myUpdatedBy = Environment.UserName;
        myUpdatedTime = DateTime.Now.ToString("YYYYMMdd HH:mm:ss zzz");
    }

    #endregion

    #region Properties

    [XmlElement("updated_by")]
    public string UpdatedBy
    {
        get { return myUpdatedBy; }
        set { myUpdatedBy = value; }
    }


    [XmlElement("updated_time")]
    public string UpdatedTime
    {
        get { return myUpdatedTime; }
        set { myUpdatedTime = value; }
    }


    #endregion

    #region Methods

    protected T[] ToArrayOfType<T>(IList<string> ids, string source)
        where T : AutoHedgerBaseDataObject, new()
    {
        T[] list = new T[] { };
        if (ids != null)
        {
            list = new T[ids.Count];
            for (int i = 0; i < ids.Count; i++)
            {
                list[i] = new T();
                list[i].Id = ids[i];
                list[i].Source = source;
            }

        }
        return list;
    }       

    #endregion
}

虽然我们有几个继承自这个基类的类,但只有一个类没有XmlInclude而无法序列化,这是一个没有可序列化属性或数据的类,并且不调用基类上的任何方法类。这是无法反序列化的类:

[Serializable()]
[XmlRoot(ElementName = "command")]
public class GetAutoHedgerHedgesCommand : AutoHedgerCommandMessage
{
    #region Constructors

    // Parameterless constructor for serialization/deserialization
    public GetAutoHedgerHedgesCommand()
        : base(Name)
    {
    }

    #endregion

    #region Constants

    public const string Name = "get_autohedger_hedges";

    #endregion        
}

1 个答案:

答案 0 :(得分:0)

大概是因为基类或派生类中的某些东西导致你的序列中没有明确提到的序列化项目列表(这个类本身不暴露任何可能导致问题的东西)。

This has been covered pretty completely in a previous question