Dieser Artikel wurde maschinell übersetzt. Wenn Sie die englische Version des Artikels anzeigen möchten, aktivieren Sie das Kontrollkästchen Englisch. Sie können den englischen Text auch in einem Popupfenster anzeigen, indem Sie den Mauszeiger über den Text bewegen.
Übersetzung
Englisch

DataContractAttribute-Klasse

 

Veröffentlicht: Oktober 2016

Gibt an, dass der Typ einen Datenvertrag definiert oder implementiert und mit einem Serialisierer wie dem DataContractSerializer serialisierbar ist. Um ihren Typ serialisierbar zu machen, müssen die Autoren hierfür einen Datenvertrag definieren.

Namespace:   System.Runtime.Serialization
Assembly:  System.Runtime.Serialization (in System.Runtime.Serialization.dll)

System.Object
  System.Attribute
    System.Runtime.Serialization.DataContractAttribute

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

NameBeschreibung
System_CAPS_pubmethodDataContractAttribute()

Initialisiert eine neue Instanz der DataContractAttribute-Klasse.

NameBeschreibung
System_CAPS_pubpropertyIsNameSetExplicitly

Ruft ab, ob Name explizit festgelegt wurde.

System_CAPS_pubpropertyIsNamespaceSetExplicitly

Ruft ab, ob Namespace explizit festgelegt wurde.

System_CAPS_pubpropertyIsReference

Ruft einen Wert ab oder legt einen Wert fest, der angibt, ob Objektverweisdaten beizubehalten sind.

System_CAPS_pubpropertyIsReferenceSetExplicitly

Ruft ab, ob IsReference explizit festgelegt wurde.

System_CAPS_pubpropertyName

Ruft den Namen des Datenvertrags für den Typ ab oder legt ihn fest.

System_CAPS_pubpropertyNamespace

Ruft den Namespace des Datenvertrags für den Typ ab oder legt ihn fest.

System_CAPS_pubpropertyTypeId

Ruft bei Implementierung in einer abgeleiteten Klasse einen eindeutigen Bezeichner für dieses Attribute ab.(Geerbt von „Attribute“.)

NameBeschreibung
System_CAPS_pubmethodEquals(Object)

Diese API unterstützt die Produkt Infrastruktur und sollte nicht direkt aus dem Code verwendet werden. Gibt einen Wert zurück, der angibt, ob diese Instanz gleich einem angegebenen Objekt ist.(Geerbt von „Attribute“.)

System_CAPS_pubmethodGetHashCode()

Gibt den Hashcode für diese Instanz zurück.(Geerbt von „Attribute“.)

System_CAPS_pubmethodGetType()

Ruft den Type der aktuellen Instanz ab.(Geerbt von „Object“.)

System_CAPS_pubmethodIsDefaultAttribute()

Gibt beim Überschreiben in einer abgeleiteten Klasse an, ob der Wert der Instanz der Standardwert für die abgeleitete Klasse ist.(Geerbt von „Attribute“.)

System_CAPS_pubmethodMatch(Object)

Ruft beim Überschreiben in einer abgeleiteten Klasse gibt einen Wert, der angibt, ob diese Instanz gleich ein angegebenen Objekt ist.(Geerbt von „Attribute“.)

System_CAPS_pubmethodToString()

Gibt eine Zeichenfolge zurück, die das aktuelle Objekt darstellt.(Geerbt von „Object“.)

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

Ordnet eine Reihe von Namen einer entsprechenden Reihe von Dispatchbezeichnern zu.(Geerbt von „Attribute“.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Ruft die Typinformationen für ein Objekt ab, mit deren Hilfe die Typinformationen für eine Schnittstelle abgerufen werden können.(Geerbt von „Attribute“.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetTypeInfoCount(UInt32)

Ruft die Anzahl der Schnittstellen mit Typinformationen ab, die von einem Objekt bereitgestellt werden (0 oder 1).(Geerbt von „Attribute“.)

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

Stellt den Zugriff auf von einem Objekt verfügbar gemachte Eigenschaften und Methoden bereit.(Geerbt von „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.

System_CAPS_cautionAchtung

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.

Weitere Informationen finden Sie unter data contracts, see the topics listed in Verwenden von Datenverträgen.

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.

System_CAPS_noteHinweis

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 "http://schemas.datacontract.org/2004/07/") 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.

System_CAPS_noteHinweis

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.

Weitere Informationen finden Sie unter versioning, see Datenvertragsversionsverwaltung.

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 = "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();
        }

    }
}

Universelle Windows-Plattform
Verfügbar seit 8
.NET Framework
Verfügbar seit 3.0
Portierbare Klassenbibliothek
Unterstützt in: portierbare .NET-Plattformen
Silverlight
Verfügbar seit 2.0
Windows Phone Silverlight
Verfügbar seit 7.0
Windows Phone
Verfügbar seit 8.1

Alle öffentlichen statischen Member ( Shared in Visual Basic) dieses Typs sind threadsicher. Die Threadsicherheit für Instanzmember ist nicht garantiert.

Zurück zum Anfang
Anzeigen: