Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.

Clase DataContractAttribute


Publicado: octubre de 2016

Especifica que el tipo define o implementa un contrato de datos y los puede serializar un serializador como, por ejemplo DataContractSerializer. Para que hacer su tipo sea serializable, los autores del tipo deben definir un contrato de datos para dicho tipo.

Espacio de nombres:   System.Runtime.Serialization
Ensamblado:  System.Runtime.Serialization (en System.Runtime.Serialization.dll)


[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, 
	Inherited = false, AllowMultiple = false)]
public sealed class DataContractAttribute : Attribute


Inicializa una nueva instancia de la clase DataContractAttribute.


Obtiene si Name se estableció explícitamente.


Obtiene si Namespace se estableció explícitamente.


Obtiene o establece un valor que indica si conservar los datos de referencia al objeto.


Obtiene si IsReference se estableció explícitamente.


Obtiene o establece el nombre del contrato de datos para el tipo.


Obtiene o establece el espacio de nombres del contrato de datos para el tipo.


Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.(Heredado de Attribute).


Esta API admite la infraestructura producto y no está diseñada para usarse directamente desde el código. Devuelve un valor que indica si esta instancia equivale al objeto especificado. (Heredado de Attribute).


Devuelve el código hash de esta instancia.(Heredado de Attribute).


Obtiene el Type de la instancia actual.(Heredado de Object).


Si se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.(Heredado de Attribute).


Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual al objeto especificado. (Heredado de Attribute).


Devuelve una cadena que representa al objeto actual. (Heredado de Object).

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.(Heredado de Attribute).

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Obtiene la información del tipo de un objeto, que puede utilizarse para obtener la información del tipo de una interfaz. (Heredado de Attribute).


Recupera el número de interfaces de tipo de información que suministra un objeto (0 ó 1)

(Heredado de Attribute).

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a las propiedades y los métodos expuestos por un objeto.(Heredado de Attribute).

Apply the T:System.Runtime.Serialization.DataContractAttribute attribute to types (classes, structures, or enumerations) that are used in serialization and deserialization operations by the T:System.Runtime.Serialization.DataContractSerializer. If you send or receive messages by using the indigo1 infrastructure, you should also apply the T:System.Runtime.Serialization.DataContractAttribute to any classes that hold and manipulate data sent in messages. crabout data contracts, see Using Data Contracts.

You must also apply the T:System.Runtime.Serialization.DataMemberAttribute to any field, property, or event that holds values you want to serialize. By applying the T:System.Runtime.Serialization.DataContractAttribute, you explicitly enable the T:System.Runtime.Serialization.DataContractSerializer to serialize and deserialize the data.


You can apply the T:System.Runtime.Serialization.DataMemberAttribute to private fields. Be aware that the data returned by the field (even if it is private) is serialized and deserialized, and thus can be viewed or intercepted by a malicious user or process.

Para obtener más información sobre data contracts, see the topics listed in Utilización de contratos de datos.

A data contract is an abstract description of a set of fields with a name and data type for each field. The data contract exists outside of any single implementation to allow services on different platforms to interoperate. As long as the data passed between the services conforms to the same contract, all the services can process the data. This processing is also known as a loosely coupled system. A data contract is also similar to an interface in that the contract specifies how data must be delivered so that it can be processed by an application. For example, the data contract may call for a data type named "Person" that has two text fields, named "FirstName" and "LastName". To create a data contract, apply the T:System.Runtime.Serialization.DataContractAttribute to the class and apply the T:System.Runtime.Serialization.DataMemberAttribute to any fields or properties that must be serialized. When serialized, the data conforms to the data contract that is implicitly built into the type.


A data contract differs significantly from an actual interface in its inheritance behavior. Interfaces are inherited by any derived types. When you apply the T:System.Runtime.Serialization.DataContractAttribute to a base class, the derived types do not inherit the attribute or the behavior. However, if a derived type has a data contract, the data members of the base class are serialized. However, you must apply the T:System.Runtime.Serialization.DataMemberAttribute to new members in a derived class to make them serializable.

If you are exchanging data with other services, you must describe the data contract. For the current version of the T:System.Runtime.Serialization.DataContractSerializer, an XML schema can be used to define data contracts. (Other forms of metadata/description could be used for the same purpose.) To create an XML schema from your application, use the Service Model Metadata Utility Tool (Svcutil.exe) with the /dconly command line option. When the input to the tool is an assembly, by default, the tool generates a set of XML schemas that define all the data contract types found in that assembly. Conversely, you can also use the Svcutil.exe tool to create Visual Basic or C# class definitions that conform to the requirements of XML schemas that use constructs that can be expressed by data contracts. In this case, the /dconly command line option is not required.

If the input to the Svcutil.exe tool is an XML schema, by default, the tool creates a set of classes. If you examine those classes, you find that the T:System.Runtime.Serialization.DataContractAttribute has been applied. You can use those classes to create a new application to process data that must be exchanged with other services.

You can also run the tool against an endpoint that returns a Web Services Description Language (WSDL) document to automatically generate the code and configuration to create an indigo1 client. The generated code includes types that are marked with the T:System.Runtime.Serialization.DataContractAttribute.

A data contract has two basic requirements: a stable name and a list of members. The stable name consists of the namespace uniform resource identifier (URI) and the local name of the contract. By default, when you apply the T:System.Runtime.Serialization.DataContractAttribute to a class, it uses the class name as the local name and the class's namespace (prefixed with "") as the namespace URI. You can override the defaults by setting the P:System.Runtime.Serialization.DataContractAttribute.Name and P:System.Runtime.Serialization.DataContractAttribute.Namespace properties. You can also change the namespace by applying the T:System.Runtime.Serialization.ContractNamespaceAttribute to the namespace. Use this capability when you have an existing type that processes data exactly as you require but has a different namespace and class name from the data contract. By overriding the default values, you can reuse your existing type and have the serialized data conform to the data contract.


In any code, you can use the word DataContract instead of the longer T:System.Runtime.Serialization.DataContractAttribute.

A data contract can also accommodate later versions of itself. That is, when a later version of the contract includes extra data, that data is stored and returned to a sender untouched. To do this, implement the T:System.Runtime.Serialization.IExtensibleDataObject interface.

Para obtener más información sobre versioning, see Versiones de contratos de datos.

The following example serializes and deserializes a class named Person to which the T:System.Runtime.Serialization.DataContractAttribute has been applied. Note that the P:System.Runtime.Serialization.DataContractAttribute.Namespace and P:System.Runtime.Serialization.DataContractAttribute.Name properties have been set to values that override the default settings.

namespace DataContractAttributeExample
    // Set the Name and Namespace properties to new values.
    [DataContract(Name = "Customer", Namespace = "")]
    class Person : IExtensibleDataObject
        // To implement the IExtensibleDataObject interface, you must also
        // implement the ExtensionData property.
        private ExtensionDataObject extensionDataObjectValue;
        public ExtensionDataObject ExtensionData
                return extensionDataObjectValue;
                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()
                Console.WriteLine("Press Enter to end");
            catch (SerializationException se)
                ("The serialization operation failed. Reason: {0}",

        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,
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
            DataContractSerializer ser =
                new DataContractSerializer(typeof(Person));
            ser.WriteObject(writer, p1);
            Console.WriteLine("Finished writing object.");
        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));


Plataforma universal de Windows
Disponible desde 8
.NET Framework
Disponible desde 3.0
Biblioteca de clases portable
Se admite en: plataformas portátiles de .NET
Disponible desde 2.0
Windows Phone Silverlight
Disponible desde 7.0
Windows Phone
Disponible desde 8.1

Cualquier miembro ( Compartido en Visual Basic) estático público de este tipo es seguro para subprocesos. No se garantiza que los miembros de instancia sean seguros para subprocesos.

Volver al principio