xsd.exe 生成的类可为空值
我一直在使用 xsd.exe 生成一个用于反序列化 XML 的类。 我在源 xsd 中有不需要的十进制值:
<xs:attribute name="Balance" type="xs:decimal" use="optional" />
xsd 生成的类生成以下代码:
private decimal balanceField;
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal Balance {
get {
return this.balanceField;
}
set {
this.balanceField = value;
}
}
我注意到它不可为空。
如何改为将字段生成为可为空,如下所示:
private decimal? balanceField;
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal? Balance {
get {
return this.balanceField;
}
set {
this.balanceField = value;
}
}
I have been using xsd.exe to generate a class for deserializing XML into.
I have decimal value in the source xsd that is not required:
<xs:attribute name="Balance" type="xs:decimal" use="optional" />
The resulting class from xsd generates the following code:
private decimal balanceField;
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal Balance {
get {
return this.balanceField;
}
set {
this.balanceField = value;
}
}
Which I note is not nullable.
How do I instead generate the field as nullable, illustrated as follows:
private decimal? balanceField;
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal? Balance {
get {
return this.balanceField;
}
set {
this.balanceField = value;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
目前它按预期工作。我正在使用 xsd v2.0.50727.42 并且:
生成您一直在寻找的内容(没有多余的
...Specified
字段和属性):Currently it works as it should. I'm using xsd v2.0.50727.42 and:
generates exactly what you've been looking for (without redundant
...Specified
field and property):我相信,如果您在 XML 架构定义中添加 nillable="true",XSD 将为该元素创建一个可以为 null 的类型。无论如何,这可能是一个好主意,因为您暗示该值确实可以为空,这将使您的模式定义在这方面更加明确。
不幸的是,在这种情况下它仍然包含相应的“指定”字段。如果您希望序列化程序直接遵循可为空值,则需要从生成的代码中手动删除“xxSpecified”列。
I believe if you add nillable="true" in your XML schema definition, XSD will create a nullable type for that element. This is probably a good idea anyway, since you are implying that this value is indeed nillable and this would make your schema definition more explicit in that regard.
Unfortunately, it still includes the corresponding "Specified" field in this case. If you want the serializer to obey the nullable value directly, you will need to manually remove the "xxSpecified" column from the generated code.
我刚刚注意到它实际上包含以下代码:
它提供了我需要的功能。
我将暂时保留这个问题,以防万一有一种优雅的方式来使用可为空的?改为键入。
I've just noticed that it has actually included the following code:
Which provides the functionality I need.
I'll leave the question open for a while in case there is an elegant way to make use of nullable? type instead.