nillable 属性绑定支持

.NET Framework 为 nillable 属性提供部分绑定支持。

说明

当在 <element> 声明中将 nillable 属性设置为 true 时,该属性允许 xsi:nil 属性出现在 XML 实例文档的符合元素中。 (前缀 xsi 通常用于表示 XML 架构实例的命名空间 http://www.w3.org/2001/XMLSchema-instance。)

XML 元素中 xsi:nil 属性的 true 值显式指定该元素没有任何内容(无论是子元素还是正文文本)。 XmlSerializer 类将 nil 属性的 true 值等同于空引用(在 Visual Basic 为 Nothing)。 有关 XmlSerializer 类如何序列化和反序列化 nil 属性(包括特殊类)的信息,请参见 xsi:nil 属性。

如果某个元素是使用 nillable="false" 声明的或者没有 nillable 属性,则无论 nil 属性的值是什么,该属性出现在对应的实例元素中都是无效的。

从代码生成 nillable 属性

当从程序集中的一组类生成 XML 架构文档时,如果值为可空类型,则 Xsd.exe 会为该类型的成员创建 nillable 属性。 这是因为可以将值类型设置为空引用 (Nothing)。

对于引用类型的对象,Xsd.exe 检查某些 XML 相关属性 (Attribute) 的 IsNullable 属性 (Property) 值。 如果 IsNullable 属性 (Property) 的值设置为 true,Xsd.exe 会创建 nillable 属性 (Attribute) 并将它的值设置为 trueIsNullable 属性 (Property) 供某些 XML 相关属性 (Attribute) 类使用。 该属性如下所示:

用法示例如下:

[System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
public string NameNullable;

Xsd.exe 从此代码生成下面的 XSD 元素声明:

<xs:element minOccurs="1" maxOccurs="1" name="NameNullable" nillable="true" type="xs:string" />

如果 IsNullable 属性 (Property) 设置为 true,并且在运行时适用的对象已设置为空引用 (Nothing),则 XmlSerializer 类生成值为 truexsi:nil 属性 (Attribute)。

应用于可为空值类型的属性 (Attribute) 的 IsNullable 属性 (Property) 必须设置为 true

对于引用类型,IsNullable 属性 (Property) 的值还决定了 <element> 元素的 minOccurs 属性 (Attribute) 值。 如果 IsNullable 的值为 true,则生成的 minOccurs 值为 1;否则值为 0。 请参见 minOccurs 属性。

在某些其他情况下,如果 IsNullable 属性未显式设置为 true,Xsd.exe 也会在 <element> 声明中生成 nillable="true" 设置。

从 nillable 属性生成代码

当遇到 nillable="true" 设置时,Xsd.exe 会为应用于生成的类或成员的相应 XML 相关属性生成一个 IsNullable=true 参数。 对于值类型,将生成可为空的类型。

可能的包含元素:<element>

请参见

参考

Xsi:nil 属性绑定支持
System.Xml.Schema.XmlSchemaElement.IsNillable

Footer image

版权所有 (C) 2007 Microsoft Corporation。保留所有权利。