本文為機器翻譯文章。如需檢視英文版,請選取 [原文] 核取方塊。您也可以將滑鼠指標移到文字上,即可在快顯視窗顯示英文原文。
譯文
原文

DataMemberAttribute 類別

 

當套用至型別的成員時,便會指定該成員屬於資料合約的一部分,而且已由 DataContractSerializer 完成序列化。

命名空間:   System.Runtime.Serialization
組件:  System.Runtime.Serialization (於 System.Runtime.Serialization.dll)

System.Object
  System.Attribute
    System.Runtime.Serialization.DataMemberAttribute

[AttributeUsageAttribute(AttributeTargets.Property | AttributeTargets.Field, 
	Inherited = false, AllowMultiple = false)]
public sealed class DataMemberAttribute : Attribute

名稱描述
System_CAPS_pubmethodDataMemberAttribute()

初始化 DataMemberAttribute 類別的新執行個體。

名稱描述
System_CAPS_pubpropertyEmitDefaultValue

取得或設定值,這個值會指定即將序列化之欄位或屬性的預設值是否要加以序列化。

System_CAPS_pubpropertyIsNameSetExplicitly

取得是否已明確設定 Name

System_CAPS_pubpropertyIsRequired

取得或設定值,這個值會指示序列化引擎在讀取或還原序列化時成員是否必須存在於其中。

System_CAPS_pubpropertyName

取得或設定資料成員名稱。

System_CAPS_pubpropertyOrder

取得或設定成員之序列化和還原序列化的順序。

System_CAPS_pubpropertyTypeId

在衍生類別中實作時,取得這個 Attribute 的唯一識別碼。(繼承自 Attribute。)

名稱描述
System_CAPS_pubmethodEquals(Object)

此 API 支援 產品 基礎結構,而且不適合直接從程式碼使用。 傳回值,這個值指出此執行個體是否與指定的物件相等。(繼承自 Attribute。)

System_CAPS_pubmethodGetHashCode()

傳回這個執行個體的雜湊碼。(繼承自 Attribute。)

System_CAPS_pubmethodGetType()

取得目前執行個體的 Type(繼承自 Object。)

System_CAPS_pubmethodIsDefaultAttribute()

在衍生類別中覆寫時,表示這個執行個體的值是衍生類別的預設值。(繼承自 Attribute。)

System_CAPS_pubmethodMatch(Object)

當在衍生類別中覆寫時,傳回值,指出這個執行個體是否等於指定的物件。(繼承自 Attribute。)

System_CAPS_pubmethodToString()

傳回代表目前物件的字串。(繼承自 Object。)

名稱描述
System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。(繼承自 Attribute。)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

擷取物件的類型資訊,可以用來取得介面的類型資訊。(繼承自 Attribute。)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetTypeInfoCount(UInt32)

擷取物件提供的類型資訊介面數目 (0 或 1)。(繼承自 Attribute。)

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

提供物件所公開的屬性和方法的存取權。(繼承自 Attribute。)

Apply the T:System.Runtime.Serialization.DataMemberAttribute attribute in conjunction with the T:System.Runtime.Serialization.DataContractAttribute to identify members of a type that are part of a data contract. One of the serializers that can serialize data contracts is the T:System.Runtime.Serialization.DataContractSerializer.

The data contract model is an "opt-in" model. Applying the T:System.Runtime.Serialization.DataMemberAttribute to a field or property explicitly specifies that the member value will be serialized. In contrast, the T:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializes public and private fields of a type, and the T:System.Xml.Serialization.XmlSerializer serializes only public fields and properties of a type.

System_CAPS_caution注意

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

By default, the CLR member name is used as the name of the data member. By setting the P:System.Runtime.Serialization.DataMemberAttribute.Name property, you can customize the name of the data member. This can be used to provide a name that may not be allowed as a CLR member name. When mapping to XML using the T:System.Runtime.Serialization.DataContractSerializer, this name is used as the name of the schema element in a type.

System_CAPS_note注意

Properties to which the T:System.Runtime.Serialization.DataMemberAttribute attribute has been applied must have both get and set fields; they cannot be get-only or set-only.

For more information about data contracts and data members, see Using Data Contracts. For more information about member names, see Data Member Default Values.

The following example shows a type to which the T:System.Runtime.Serialization.DataContractAttribute and T:System.Runtime.Serialization.DataMemberAttribute attributes have been applied. The P:System.Runtime.Serialization.DataMemberAttribute.Name property on the T:System.Runtime.Serialization.DataMemberAttribute is set to "ID".

using System;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

// You must apply a DataContractAttribute or SerializableAttribute
// to a class to have it serialized by the DataContractSerializer.
[DataContract()]
class Person : IExtensibleDataObject
{
    private string LastNameValue;
    // Apply the DataMemberAttribute to fields (or properties) 
    // that must be serialized.
    [DataMember()]
    public string FirstName;

    [DataMember]
    public string LastName
    {
        get { return LastNameValue; }
        set { LastNameValue = value; }
    }

    [DataMember(Name = "ID")]
    public int IdNumber;

    // Note that you can apply the DataMemberAttribute to 
    // a private field as well.
    [DataMember]
    private string Secret;

    public Person(string newfName, string newLName, int newIdNumber)
    {
        FirstName = newfName;
        LastName = newLName;
        IdNumber = newIdNumber;
        Secret = newfName + newLName + newIdNumber;
    }

    // The extensionDataValue field holds data from future versions 
    // of the type.  This enables this type to be compatible with 
    // future versions. The field is required to implement the 
    // IExtensibleDataObject interface.

    private ExtensionDataObject extensionDatavalue;

    public ExtensionDataObject ExtensionData
    {
        get
        {
            return extensionDatavalue;
        }
        set
        {
            extensionDatavalue = value;
        }
    }
}

public class Test
{
    public static void Main(string[] args)
    {
        try
        {
            WriteObject(@"DataMemberAttributeExample.xml");
            ReadObject(@"DataMemberAttributeExample.xml");
        }
        catch (Exception exc)
        {
            Console.WriteLine(
            "The serialization operation failed: {0} StackTrace: {1}",
            exc.Message, exc.StackTrace);
        }
        finally
        {
            Console.WriteLine("Press <Enter> to exit....");
            Console.ReadLine();
        }
    }

    public static void WriteObject(string filename)
    {
        // Create a new instance of the Person class.
        Person p1 = new Person("Zighetti", "Barbara", 101);
        FileStream writer = new FileStream(filename,
        FileMode.OpenOrCreate);
        DataContractSerializer ser =
            new DataContractSerializer(typeof(Person));
        ser.WriteObject(writer, p1);
        writer.Close();
    }

    public static void ReadObject(string filename)
    {
        // Deserialize an instance of the Person class 
        // from an XML file.
        FileStream fs = new FileStream(filename,
        FileMode.OpenOrCreate);
        DataContractSerializer ser =
            new DataContractSerializer(typeof(Person));
        // Deserialize the data and read it from the instance.
        Person deserializedPerson = (Person)ser.ReadObject(fs);
        fs.Close();
        Console.WriteLine(String.Format("{0} {1}, ID: {2}",
        deserializedPerson.FirstName, deserializedPerson.LastName,
        deserializedPerson.IdNumber));
    }

}

通用 Windows 平台
自 8 起供應
.NET Framework
自 3.0 起供應
可攜式類別庫
提供支援︰ 可攜式 .NET 平台
Silverlight
自 2.0 起供應
Windows Phone Silverlight
自 7.0 起供應
Windows Phone
自 8.1 起供應

此類型的任何 public static (在 Visual Basic 中 共用 在 Visual Basic 中) 成員皆為安全執行緒。不保證任何執行個體成員為安全執行緒。

回到頁首
顯示: