DataContractAttribute 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
指定类型定义或实现数据协定,并由序列化程序序列化,例如 DataContractSerializer。 若要使其类型可序列化,类型作者必须为其类型定义数据协定。
public ref class DataContractAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Struct, AllowMultiple=false, Inherited=false)]
public sealed class DataContractAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Struct, AllowMultiple=false, Inherited=false)>]
type DataContractAttribute = class
inherit Attribute
Public NotInheritable Class DataContractAttribute
Inherits Attribute
- 继承
- 属性
示例
以下示例序列化和反序列化已应用该类的类PersonDataContractAttribute。 请注意,属性NamespaceName已设置为替代默认设置的值。
namespace DataContractAttributeExample
{
// Set the Name and Namespace properties to new values.
[DataContract(Name = "Customer", Namespace = "http://www.contoso.com")]
class Person : IExtensibleDataObject
{
// To implement the IExtensibleDataObject interface, you must also
// implement the ExtensionData property.
private ExtensionDataObject extensionDataObjectValue;
public ExtensionDataObject ExtensionData
{
get
{
return extensionDataObjectValue;
}
set
{
extensionDataObjectValue = value;
}
}
[DataMember(Name = "CustName")]
internal string Name;
[DataMember(Name = "CustID")]
internal int ID;
public Person(string newName, int newID)
{
Name = newName;
ID = newID;
}
}
class Test
{
public static void Main()
{
try
{
WriteObject("DataContractExample.xml");
ReadObject("DataContractExample.xml");
Console.WriteLine("Press Enter to end");
Console.ReadLine();
}
catch (SerializationException se)
{
Console.WriteLine
("The serialization operation failed. Reason: {0}",
se.Message);
Console.WriteLine(se.Data);
Console.ReadLine();
}
}
public static void WriteObject(string path)
{
// Create a new instance of the Person class and
// serialize it to an XML file.
Person p1 = new Person("Mary", 1);
// Create a new instance of a StreamWriter
// to read and write the data.
FileStream fs = new FileStream(path,
FileMode.Create);
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
DataContractSerializer ser =
new DataContractSerializer(typeof(Person));
ser.WriteObject(writer, p1);
Console.WriteLine("Finished writing object.");
writer.Close();
fs.Close();
}
public static void ReadObject(string path)
{
// Deserialize an instance of the Person class
// from an XML file. First create an instance of the
// XmlDictionaryReader.
FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
XmlDictionaryReader reader =
XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
// Create the DataContractSerializer instance.
DataContractSerializer ser =
new DataContractSerializer(typeof(Person));
// Deserialize the data and read it from the instance.
Person newPerson = (Person)ser.ReadObject(reader);
Console.WriteLine("Reading this object:");
Console.WriteLine(String.Format("{0}, ID: {1}",
newPerson.Name, newPerson.ID));
fs.Close();
}
}
}
Namespace DataContractAttributeExample
' Set the Name and Namespace properties to new values.
<DataContract(Name := "Customer", [Namespace] := "http://www.contoso.com")> _
Class Person
Implements IExtensibleDataObject
' To implement the IExtensibleDataObject interface, you must also
' implement the ExtensionData property.
Private extensionDataObjectValue As ExtensionDataObject
Public Property ExtensionData() As ExtensionDataObject _
Implements IExtensibleDataObject.ExtensionData
Get
Return extensionDataObjectValue
End Get
Set
extensionDataObjectValue = value
End Set
End Property
<DataMember(Name := "CustName")> _
Friend Name As String
<DataMember(Name := "CustID")> _
Friend ID As Integer
Public Sub New(ByVal newName As String, ByVal newID As Integer)
Name = newName
ID = newID
End Sub
End Class
Class Test
Public Shared Sub Main()
Try
WriteObject("DataContractExample.xml")
ReadObject("DataContractExample.xml")
Console.WriteLine("Press Enter to end")
Console.ReadLine()
Catch se As SerializationException
Console.WriteLine("The serialization operation failed. Reason: {0}", _
se.Message)
Console.WriteLine(se.Data)
Console.ReadLine()
End Try
End Sub
Public Shared Sub WriteObject(ByVal path As String)
' Create a new instance of the Person class and
' serialize it to an XML file.
Dim p1 As New Person("Mary", 1)
' Create a new instance of a StreamWriter
' to read and write the data.
Dim fs As New FileStream(path, FileMode.Create)
Dim writer As XmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(fs)
Dim ser As New DataContractSerializer(GetType(Person))
ser.WriteObject(writer, p1)
Console.WriteLine("Finished writing object.")
writer.Close()
fs.Close()
End Sub
Public Shared Sub ReadObject(ByVal path As String)
' Deserialize an instance of the Person class
' from an XML file. First create an instance of the
' XmlDictionaryReader.
Dim fs As New FileStream(path, FileMode.OpenOrCreate)
Dim reader As XmlDictionaryReader = XmlDictionaryReader. _
CreateTextReader(fs, New XmlDictionaryReaderQuotas())
' Create the DataContractSerializer instance.
Dim ser As New DataContractSerializer(GetType(Person))
' Deserialize the data and read it from the instance.
Dim newPerson As Person = CType(ser.ReadObject(reader), Person)
Console.WriteLine("Reading this object:")
Console.WriteLine(String.Format("{0}, ID: {1}", newPerson.Name, newPerson.ID))
fs.Close()
End Sub
End Class
End Namespace
注解
将 DataContractAttribute 特性应用于由 DataContractSerializer 在序列化和反序列化操作中使用的类型(类、结构或枚举)。 如果使用 Windows Communication Foundation(WCF)基础结构来发送或接收消息,则还应将 DataContractAttribute 应用于保存及操控消息中发送数据的任何类。 有关数据协定的详细信息,请参阅 “使用数据协定”。
您还必须将 DataMemberAttribute 应用于包含您想要序列化的值的任何字段、属性或事件。 通过应用DataContractAttribute,您可以显式启用DataContractSerializer的序列化和反序列化功能。
Caution
你可以应用 DataMemberAttribute 到私有字段。 请注意,字段返回的数据(即使为专用数据)已序列化和反序列化,因此可由恶意用户或进程查看或拦截。
有关数据协定的详细信息,请参阅 “使用数据协定”中列出的主题。
数据协定
数据协定是一组字段的抽象说明,其中包含每个字段的名称和数据类型。 数据协定存在于任何单个实现之外,以允许不同平台上的服务进行互作。 只要服务之间传递的数据符合同一协定,所有服务都可以处理数据。 此处理也称为 松散耦合系统。 数据协定也类似于接口,该协定指定如何传递数据,以便应用程序可以处理数据。 例如,数据协定可能会调用名为“Person”的数据类型,该数据类型具有两个文本字段,名为“FirstName”和“LastName”。 若要创建数据协定,请将 DataContractAttribute 应用于类,并将 DataMemberAttribute 应用于任何必须序列化的字段或属性。 序列化后,数据符合隐式内置到类型中的数据协定。
注释
数据协定与其继承行为中的实际接口明显不同。 接口由任何派生类型继承。 当您将 DataContractAttribute 应用于基类时,派生类型不会继承该属性或行为。 但是,如果派生类型具有数据协定,则会序列化基类的数据成员。 但是,您必须在派生类中将 DataMemberAttribute 应用于新的成员,以使其可序列化。
XML 架构文档和 SvcUtil 工具
如果要与其他服务交换数据,则必须描述数据协定。 对于当前版本的 DataContractSerializerXML 架构,可用于定义数据协定。 (其他类型的元数据/说明可用于同一目的。若要从应用程序创建 XML 架构,请使用 ServiceModel 元数据实用工具工具(Svcutil.exe) 和 /dconly 命令行选项。 默认情况下,当工具的输入是程序集时,该工具将生成一组 XML 架构,用于定义该程序集中找到的所有数据协定类型。 相反,还可以使用 Svcutil.exe 工具创建 Visual Basic 或 C# 类定义,这些定义符合使用可由数据协定表示的构造的 XML 架构的要求。 在这种情况下,不需要 /dconly 命令行选项。
如果对 Svcutil.exe 工具的输入是 XML 架构,则默认情况下,该工具将创建一组类。 如果您检查这些类,您会发现 DataContractAttribute 已被应用。 可以使用这些类创建新的应用程序来处理必须与其他服务交换的数据。
还可以针对返回 Web 服务描述语言(WSDL)文档的终结点运行该工具,以自动生成代码和配置以创建 Windows Communication Foundation (WCF) 客户端。 生成的代码包括用 DataContractAttribute.. 标记的类型。
重用现有类型
数据协定有两个基本要求:稳定名称和成员列表。 稳定名称由命名空间统一资源标识符(URI)和协定的本地名称组成。 默认情况下,在将类应用于 DataContractAttribute 类时,它将类名用作本地名称,类的命名空间(前缀为 "http://schemas.datacontract.org/2004/07/")作为命名空间 URI。 可以通过设置 Name 和 Namespace 属性来替代默认值。 您还可以通过将 ContractNamespaceAttribute 应用于命名空间来更改命名空间。 当你有一个现有类型可以完全按照要求处理数据,但它具有与数据契约不同的命名空间和类名时,请使用此功能。 通过重写默认值,可以重复使用现有类型,并使序列化数据符合数据协定。
注释
在任何代码中,你可以使用DataContract这个单词来代替较长的DataContractAttribute。
版本管理
数据协定还可以与其自身的后续版本兼容。 也就是说,当更高版本的协定包含额外的数据时,该数据将存储和返回给未接触的发送方。 为此,请实现 IExtensibleDataObject 接口。
有关版本控制的详细信息,请参阅 数据协定版本控制。
构造函数
| 名称 | 说明 |
|---|---|
| DataContractAttribute() |
初始化 DataContractAttribute 类的新实例。 |
属性
| 名称 | 说明 |
|---|---|
| IsNameSetExplicitly |
获取是否已 Name 显式设置。 |
| IsNamespaceSetExplicitly |
获取是否已 Namespace 显式设置。 |
| IsReference |
获取或设置一个值,该值指示是否保留对象引用数据。 |
| IsReferenceSetExplicitly |
获取是否已 IsReference 显式设置。 |
| Name |
获取或设置类型的数据协定的名称。 |
| Namespace |
获取或设置类型的数据协定的命名空间。 |
| TypeId |
在派生类中实现时,获取此 Attribute的唯一标识符。 (继承自 Attribute) |
方法
| 名称 | 说明 |
|---|---|
| Equals(Object) |
返回一个值,该值指示此实例是否等于指定对象。 (继承自 Attribute) |
| GetHashCode() |
返回此实例的哈希代码。 (继承自 Attribute) |
| GetType() |
获取当前实例的 Type。 (继承自 Object) |
| IsDefaultAttribute() |
在派生类中重写时,指示此实例的值是否为派生类的默认值。 (继承自 Attribute) |
| Match(Object) |
在派生类中重写时,返回一个值,该值指示此实例是否等于指定对象。 (继承自 Attribute) |
| MemberwiseClone() |
创建当前 Object的浅表副本。 (继承自 Object) |
| ToString() |
返回一个表示当前对象的字符串。 (继承自 Object) |
显式接口实现
| 名称 | 说明 |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
将一组名称映射为对应的一组调度标识符。 (继承自 Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
检索对象的类型信息,该信息可用于获取接口的类型信息。 (继承自 Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
检索对象提供的类型信息接口的数量(0 或 1)。 (继承自 Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
提供对对象公开的属性和方法的访问。 (继承自 Attribute) |