.Net 设置文件、复杂类型和序列化
我有以下类型
[Serializable, XmlType(Namespace="http://mycompany/foo"]
public sealed class Limit
{
[XmlElement(ElementName="Value1")]
public double Value1 {get;set;}
[XmlElement(ElementName="ComplexValue1")]
public ComplexValue ComplexValue1 {get;set;}
}
[Serializable, XmlType(Namespace="http://mycompany/foo"]
public sealed class ComplexValue
{
[XmlElement(ElementName="Item1")]
public double Item1 {get;set;}
[XmlElement(ElementName="Item2")]
public double Item2 {get;set;}
}
,我想将其序列化为 .settings 文件。
当我将下面的 blob 复制到设置文件中时,我以某种方式丢失了 ComplexValue1 元素:
<?xml version="1.0" encoding="utf-16"?>
<Limit>
<Value1>20</Value1>
<ComplexValue1>
<Item1>2.0</Item1>
<Item2>5.0</Item2>
</ComplexValue1>
</Limit>
即 Visual Studio 将其转换为:
<?xml version="1.0" encoding="utf-16"?>
<Limit>
<Value1>20</Value1>
</Limit>
带有一堆我认为对问题无关的命名空间...
我缺少什么?
I have the following types
[Serializable, XmlType(Namespace="http://mycompany/foo"]
public sealed class Limit
{
[XmlElement(ElementName="Value1")]
public double Value1 {get;set;}
[XmlElement(ElementName="ComplexValue1")]
public ComplexValue ComplexValue1 {get;set;}
}
[Serializable, XmlType(Namespace="http://mycompany/foo"]
public sealed class ComplexValue
{
[XmlElement(ElementName="Item1")]
public double Item1 {get;set;}
[XmlElement(ElementName="Item2")]
public double Item2 {get;set;}
}
which I want to serialize to a .settings file.
When I copy the blob below into the settings file, I lose the ComplexValue1 element somehow:
<?xml version="1.0" encoding="utf-16"?>
<Limit>
<Value1>20</Value1>
<ComplexValue1>
<Item1>2.0</Item1>
<Item2>5.0</Item2>
</ComplexValue1>
</Limit>
i.e. Visual Studio transforms it to:
<?xml version="1.0" encoding="utf-16"?>
<Limit>
<Value1>20</Value1>
</Limit>
with a bunch of namespaces that I think don't matter for the question...
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要用于 XML 序列化的
Serializable
属性我想您应该这样做删除
XmlType
属性来解决问题。您指定了命名空间,但 XML 文件中没有命名空间?这应该也适合。
如果您愿意,请使用
XmlRoot
作为根节点You don't need the
Serializable
attribute for XML serializationI guess you should remove the
XmlType
attribute to solve the issue.You specify a namespace but there are none in the XML file? This should fit too.
Use
XmlRoot
for the root node if you like可以在设置设计器中的每个设置基础上关闭生成默认值的代码。对于那些不需要的设置,只需在属性窗口中将GenerateDefaultValueInCode 设置为 false 即可。
Generating the code for the default value can be switched off on a per-setting base within the Setting designer. Just set GenerateDefaultValueInCode to false within the property window for those settings that don't need it.