我正在尝试序列化一个派生自 BindingList(Floor) 的类,其中 Floor 是一个简单的类,仅包含属性 Floor.Height
这是我的类(class)的简化版本
[Serializable]
[XmlRoot(ElementName = "CustomBindingList")]
public class CustomBindingList:BindingList<Floor>
{
[XmlAttribute("publicField")]
public string publicField;
private string privateField;
[XmlAttribute("PublicProperty")]
public string PublicProperty
{
get { return privateField; }
set { privateField = value; }
}
}
我将使用以下代码序列化 CustomBindingList 的实例。
XmlSerializer ser = new XmlSerializer(typeof(CustomBindingList));
StringWriter sw = new StringWriter();
CustomBindingList cLIst = new CustomBindingList();
Floor fl;
fl = new Floor();
fl.Height = 10;
cLIst.Add(fl);
fl = new Floor();
fl.Height = 10;
cLIst.Add(fl);
fl = new Floor();
fl.Height = 10;
cLIst.Add(fl);
ser.Serialize(sw, cLIst);
string testString = sw.ToString();
但是上面的 testString 结束后被设置为以下 XML:
<CustomBindingList xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<Floor Height="10" />
<Floor Height="10" />
<Floor Height="10" />
</CustomBindingList>"
如何让“publicField”或“publicProperty也进行序列化?
最佳答案
这里的简短回答是,.NET 通常期望某个成为集合异或具有属性。这体现在几个地方:
- xml 序列化;集合的属性未序列化
- 数据绑定(bind);您无法将数据绑定(bind)到集合上的属性,因为它会隐式将您带到第一项
在 xml 序列化的情况下,如果您认为它可能只是客户端的 SomeType[]
,那么这是有道理的……额外的数据会去哪里?
常见的解决方案是封装一个集合 - 即而不是
public class MyType : List<MyItemType> // or BindingList<...>
{
public string Name {get;set;}
}
public class MyType
{
public string Name {get;set;}
public List<MyItemType> Items {get;set;} // or BindingList<...>
}
通常情况下,我不会在集合属性上设置 set
,但 XmlSerializer
需要它...
关于c# - 从 BindingList<T> 派生的类的公共(public)字段/属性不会序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1225750/