0

我在这里遇到了多个问题和答案,但没有针对我的情况。

我有一个类“实体”,其中包含多个从它延伸出来的类。我希望序列化能够命中列表并理解并使用每个项目的类型作为节点名称。

现在,我可以使用注释掉的内容(定义主类中的每个数组项并使用 [XmlArrayItem("Subclass1", typeof(subclass1)] 定义此类项的名称,但我想将所有定义保留在它们的子类中,我将有太多的子类来定义主实体类中的所有内容......有没有办法实现这一点?

我曾尝试将 [XmlType(TypeName="...")] 用于子类等等,但这不起作用。

[Serializable]
[XmlInclude(typeof(Subclass1))]
[XmlRoot("Entity")]
public class Entity{

    [XmlArray("CausedBy")]
    //[XmlArrayItem("Subclass1", typeof(subclass1))]
    //[XmlArrayItem("Sublcass2", typeof(Subclass2))]
    public List<Entity> CausedBy { get; set; }

}

[Serializable]
[XmlRoot("Subclass1")]
[XmlInclude(typeof(Subclass2))]
public class Subclass1:Entity{
    //Code...
}

[Serializable]
[XmlRoot("Subclass2")]
public class Subclass2:Subclass1{
  //Code...
}

在创建实体并将 Subclass1 和 Subclass2 添加到列表 'CausedBy' 类后序列化上述代码会产生以下结果:

<Entity>
  <CausedBy>
    <Entity ... xsi:type="SubClass1" />
    <Entity ... xsi:type="SubClass2" />
   </CausedBy>
<Entity>

我希望输出显示:

 <Entity>
      <CausedBy>
        <SubClass1 .../>
        <SubClass2 .../>
       </CausedBy>
    <Entity>
4

2 回答 2

1

由于我一开始就完全没有阅读这个问题,所以这是一个新的答案(它有点 tl;dr,所以你总是可以跳到最后并点击链接):

不可能让内置的序列化程序类工作,因为您不希望添加它需要能够操作的属性。您唯一的选择是自己对课程进行连续化,但是,这不必像听起来那样乏味;几年前,我在虚拟模式下使用 DataGridView 时遇到了类似的问题,并生成了一个通用虚拟器,可用于虚拟化数据以进行显示;它使用了一个自定义属性:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class showColumnAttribute : System.Attribute
{
    ///<summary>Optional display format for column</summary>
    public string Format;
    ///<summary>Optional Header string for column<para>Defaults to propety name</para></summary>
    public string Title;
    ///<summary>Optional column edit flag - defaults to false</summary>
    public bool ReadOnly;
    ///<summary>Optional column width</summary>
    public int Width;
    ///<summary>
    ///Marks public properties that are to be displayed in columns
    ///</summary>
    public showColumnAttribute()
    {
        Format = String.Empty;
        Title = String.Empty;
        ReadOnly = false;
        Width = 0;
    }
}

和一个构造函数:

    ///<summary>
    ///Extracts the properties of the supplied type that are to be displayed
    ///<para>The type must be a class or an InvalidOperationException will be thrown</para>
    ///</summary>
    public Virtualiser(Type t)
    {
        if (!t.IsClass)
            throw new InvalidOperationException("Supplied type is not a class");

        List<VirtualColumnInfo> definedColumns = new List<VirtualColumnInfo>();
        PropertyInfo[] ps = t.GetProperties();
        MethodInfo mg, ms;

        for (int i = 0; i < ps.Length; i++)
        {
            Object[] attr = ps[i].GetCustomAttributes(true);

            if (attr.Length > 0)
            {
                foreach (var a in attr)
                {
                    showColumnAttribute ca = a as showColumnAttribute;
                    if (ca != null)
                    {
                        mg = ps[i].GetGetMethod();
                        if (mg != null)
                        {
                            ms = ps[i].GetSetMethod();
                            definedColumns.Add
                            (
                                new VirtualColumnInfo
                                (
                                    ps[i].Name, ca.Width, ca.ReadOnly, ca.Title == String.Empty ? ps[i].Name : ca.Title, 
                                    ca.Format, mg, ms
                                )
                            );
                        }
                        break;
                    }
                }
            }
        }
        if (definedColumns.Count > 0)
            columns = definedColumns.ToArray();
    }

这会提取类的公共属性,并将标记的项目作为列连同标题、格式等提供给 DataGridView。

所有这些(以及其余缺失代码)的效果是,任何类型都可以在 dataGridView 中虚拟化,只需标记公共属性并为给定类型调用一次虚拟器:

    #region Virtualisation
    static readonly Virtualiser Virtual = new Virtualiser(typeof(UserRecord));
    [XmlIgnore] // just in case!
    public static int ColumnCount { get { return Virtual.ColumnCount; } }
    public static VirtualColumnInfo ColumnInfo(int column)
    {
        return Virtual.ColumnInfo(column);
    }

    public Object GetItem(int column)
    {
        return Virtual.GetItem(column, this);
    }
    /*
    ** The supplied item should be a string - it is up to this method to supply a valid value to the property
    ** setter (this is the simplest place to determine what this is and how it can be derived from a string).
    */
    public void SetItem(int column, Object item)
    {
        String v = item as String;
        int t = 0;
        if (v == null)
            return;
        switch (Virtual.GetColumnPropertyName(column))
        {
            case "DisplayNumber":
                if (!int.TryParse(v, out t))
                    t = 0;

                item = t;
                break;
        }
        try
        {
            Virtual.SetItem(column, this, item);
        }
        catch { }
    }
    #endregion

列数、它们的属性和顺序可以通过创建一些从类数据派生的公共属性来自动指定:

        #region Display columns
    [showColumn(ReadOnly = true, Width = 100, Title = "Identification")]
    public String DisplayIdent
    {
        get
        {
            return ident;
        }
        set
        {
            ident = value;
        }

    }
    [showColumn(Width = 70, Title = "Number on Roll")]
    public int DisplayNumber
    {
        get
        {
            return number;
        }
        set
        {
            number = value;
        }
    }
    [showColumn(Width = -100, Title = "Name")]
    public string DisplayName
    {
        get
        {
            return name == String.Empty ? "??" : name;
        }
        set
        {
            name = value;
        }
    }
    #endregion

这将为 dataGridView 虚拟化任何类以显示和编辑数据,多年来我多次使用它,提取要显示的属性正是 XML 序列化所需要的,实际上,它具有许多相同的特性。

我打算采用这种方法来为 XML 序列化做同样的工作,但有人已经在https://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=474453完成了它,我希望你可以使用这个方法来解决你的问题。

于 2017-09-21T10:17:38.380 回答
0

这对我有用:

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Entity entity = new Entity();
        entity.CausedBy = new List<Entity>();
        entity.CausedBy.Add(new Subclass1());
        entity.CausedBy.Add(new Subclass2());
        entity.CausedBy.Add(new Subclass2());
        entity.CausedBy.Add(new Subclass1());
        entity.CausedBy.Add(new Subclass1());
        entity.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Test.txt"));
    }
}
[Serializable]
[XmlRoot("Entity")]
public class Entity
{
    [XmlArray("CausedBy")]
    [XmlArrayItem("SubClass1", typeof(Subclass1))]
    [XmlArrayItem("SubClass2", typeof(Subclass2))]
    public List<Entity> CausedBy { get; set; }

}

[Serializable]
[XmlRoot("Subclass1")]
public class Subclass1 : Entity
{
    [XmlIgnore]
    String t = DateTime.Now.ToShortDateString();

    public String SubClass1Item { get { return "Test1 " + t; } set { } }
}

[Serializable]
[XmlRoot("Subclass2")]
public class Subclass2 : Entity
{
    [XmlIgnore]
    String t = DateTime.Now.ToString();

    public String SubClass2Item { get { return "Test2 " + t; } set { } }
}

它产生:

<Entity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <CausedBy>
    <SubClass1>
      <SubClass1Item>Test1 20/09/2017</SubClass1Item>
    </SubClass1>
    <SubClass2>
      <SubClass2Item>Test2 20/09/2017 01:06:55</SubClass2Item>
    </SubClass2>
    <SubClass2>
      <SubClass2Item>Test2 20/09/2017 01:06:55</SubClass2Item>
    </SubClass2>
    <SubClass1>
      <SubClass1Item>Test1 20/09/2017</SubClass1Item>
    </SubClass1>
    <SubClass1>
      <SubClass1Item>Test1 20/09/2017</SubClass1Item>
    </SubClass1>
  </CausedBy>
</Entity>
于 2017-09-20T00:10:19.607 回答