gpt4 book ai didi

C#类序列化映射

转载 作者:数据小太阳 更新时间:2023-10-29 02:12:06 25 4
gpt4 key购买 nike

我正在寻找有关如何实现和/或更改一般以下类的类序列化行为的提示和想法。

简化的(不完整的)示例类:

[Serializable]
public class Choobakka
{
public string Name { get; set; }
public VariableList<Item> Stuff { get; set; }
}
[Serializable]
public class Item
{
public string Name { get; set; }
public string Value { get; set; }
}
[Serializable]
public sealed class VariableList<T> : AVariableList<T>
{
public new ItemList<T> Items { get { return _items; } set { _items = value; } }
public new bool IsNull { get { return Items == null; } }
public new bool IsEmpty { get { return IsNull || Count <= 0; } }
public new int Count { get { return IsNull ? 0 : this.Items.Count; } }
public new string CountAsString { get { return Count.ToString(); } }
public VariableList()
{
_items = new ItemList<T>();
}
}

这就是我填写和连载 Choobakka 的东西的方式

var choobakka = new Choobakka() { Name = "CHOO-BAKKA", Stuff = new VariableList<Item>()  };            
choobakka.Stuff.Items.Add( new Item() { Name = "passport", Value = "lv" } );
choobakka.Stuff.Items.Add( new Item() { Name = "wallet", Value = "50euro" } );
StringBuilder sb = new StringBuilder();
using (TextWriter tw = new StringWriter(sb))
{
XmlSerializer xs = new XmlSerializer(typeof(Choobakka));
xs.Serialize(tw, choobakka);
}

序列化的 XML 看起来像:

<Choobakka>
<Name>CHOO-BAKKA</Name>
<Stuff>
<Items>
<Item>
<Name>passport</Name>
<Value>lv</Value>
</Item>
<Item>
<Name>wallet</Name>
<Value>50euro</Value>
</Item>
</Items>
</Stuff>
</Choobakka>

现在的问题是您建议如何获得 <Items> 的装备标记(如果可能)类似

<Choobakka>
<Name>CHOO-BAKKA</Name>
<Stuff>
<Item>
<Name>passport</Name>
<Value>lv</Value>
</Item>
<Item>
<Name>wallet</Name>
<Value>50euro</Value>
</Item>
</Stuff>
</Choobakka>

话虽如此,我无法更改 VariableList<T> 的结构类,除了应用一些 XML 序列化属性。

这样做的原因不仅是简化生成的 XML,而且还对 SQL Server 查询生成的 XML 进行反序列化。我有属性的想法,xsd/xslt转换...

最佳答案

如果你不能改变VariableList<> , 然后改变 Choobaka会做

public class Choobakka
{
public string Name { get; set; }
[XmlIgnore]
public VariableList<Item> Stuff { get; set; } // we do not serialize this
[XmlArray("Stuff")]
public Item[] _Stuff // but this
{
get
{
// get Item[] from Stuff property somehow
// ...

// as test
return new Item[] {new Item() { Name = "1", Value = "111"}, new Item() { Name = "2", Value = "222"}};
}
set
{
// set Stuff property from Item[] somehow
// ...
}
}
}

产生(proof)

<?xml version="1.0" encoding="utf-16"?>
<Choobakka xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name>CHOO-BAKKA</Name>
<Stuff>
<Item>
<Name>1</Name>
<Value>111</Value>
</Item>
<Item>
<Name>2</Name>
<Value>222</Value>
</Item>
</Stuff>
</Choobakka>

关于C#类序列化映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29916402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com