XmlChoiceIdentifierAttribute Kelas
Definisi
Penting
Beberapa informasi terkait produk prarilis yang dapat diubah secara signifikan sebelum dirilis. Microsoft tidak memberikan jaminan, tersirat maupun tersurat, sehubungan dengan informasi yang diberikan di sini.
Menentukan bahwa anggota dapat dideteksi lebih lanjut dengan menggunakan enumerasi.
public ref class XmlChoiceIdentifierAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=false)]
public class XmlChoiceIdentifierAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=false)>]
type XmlChoiceIdentifierAttribute = class
inherit Attribute
Public Class XmlChoiceIdentifierAttribute
Inherits Attribute
- Warisan
- Atribut
Contoh
Contoh berikut menserialisasikan kelas bernama Choices yang menyertakan dua bidang, MyChoice dan ManyChoices.
XmlChoiceIdentifierAttribute diterapkan ke setiap bidang yang menentukan (melalui MemberName properti) anggota kelas lain yang mendapatkan atau mengatur enumerasi yang mendeteksi nilai anggota. Bidang MyChoice dapat diatur ke satu nilai, dengan anggota enumerasi terkait yang ditemukan di EnumType bidang . Bidang ManyChoices mengembalikan array objek. Bidang ChoiceArray mengembalikan array nilai enumerasi. Untuk setiap anggota array di ManyChoices bidang , anggota terkait ditemukan dalam array yang dikembalikan oleh ChoiceArray bidang .
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
public class Choices{
// The MyChoice field can be set to any one of
// the types below.
[XmlChoiceIdentifier("EnumType")]
[XmlElement("Word", typeof(string))]
[XmlElement("Number", typeof(int))]
[XmlElement("DecimalNumber", typeof(double))]
public object MyChoice;
// Don't serialize this field. The EnumType field
// contains the enumeration value that corresponds
// to the MyChoice field value.
[XmlIgnore]
public ItemChoiceType EnumType;
// The ManyChoices field can contain an array
// of choices. Each choice must be matched to
// an array item in the ChoiceArray field.
[XmlChoiceIdentifier("ChoiceArray")]
[XmlElement("Item", typeof(string))]
[XmlElement("Amount", typeof(int))]
[XmlElement("Temp", typeof(double))]
public object[] ManyChoices;
// TheChoiceArray field contains the enumeration
// values, one for each item in the ManyChoices array.
[XmlIgnore]
public MoreChoices[] ChoiceArray;
}
[XmlType(IncludeInSchema=false)]
public enum ItemChoiceType{
None,
Word,
Number,
DecimalNumber
}
public enum MoreChoices{
None,
Item,
Amount,
Temp
}
public class Test{
static void Main(){
Test t = new Test();
t.SerializeObject("Choices.xml");
t.DeserializeObject("Choices.xml");
}
private void SerializeObject(string filename){
XmlSerializer mySerializer =
new XmlSerializer(typeof(Choices));
TextWriter writer = new StreamWriter(filename);
Choices myChoices = new Choices();
// Set the MyChoice field to a string. Set the
// EnumType to Word.
myChoices.MyChoice= "Book";
myChoices.EnumType = ItemChoiceType.Word;
// Populate an object array with three items, one
// of each enumeration type. Set the array to the
// ManyChoices field.
object[] strChoices = new object[]{"Food", 5, 98.6};
myChoices.ManyChoices=strChoices;
// For each item in the ManyChoices array, add an
// enumeration value.
MoreChoices[] itmChoices = new MoreChoices[]
{MoreChoices.Item,
MoreChoices.Amount,
MoreChoices.Temp};
myChoices.ChoiceArray=itmChoices;
mySerializer.Serialize(writer, myChoices);
writer.Close();
}
private void DeserializeObject(string filename){
XmlSerializer ser = new XmlSerializer(typeof(Choices));
// A FileStream is needed to read the XML document.
FileStream fs = new FileStream(filename, FileMode.Open);
Choices myChoices = (Choices)
ser.Deserialize(fs);
fs.Close();
// Disambiguate the MyChoice value using the enumeration.
if(myChoices.EnumType == ItemChoiceType.Word){
Console.WriteLine("Word: " +
myChoices.MyChoice.ToString());
}
else if(myChoices.EnumType == ItemChoiceType.Number){
Console.WriteLine("Number: " +
myChoices.MyChoice.ToString());
}
else if(myChoices.EnumType == ItemChoiceType.DecimalNumber){
Console.WriteLine("DecimalNumber: " +
myChoices.MyChoice.ToString());
}
// Disambiguate the ManyChoices values using the enumerations.
for(int i = 0; i<myChoices.ManyChoices.Length; i++){
if(myChoices.ChoiceArray[i] == MoreChoices.Item)
Console.WriteLine("Item: " + (string) myChoices.ManyChoices[i]);
else if(myChoices.ChoiceArray[i] == MoreChoices.Amount)
Console.WriteLine("Amount: " + myChoices.ManyChoices[i].ToString());
if(myChoices.ChoiceArray[i] == MoreChoices.Temp)
Console.WriteLine("Temp: " + (string) myChoices.ManyChoices[i].ToString());
}
}
}
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO
Public Class Choices
' The MyChoice field can be set to any one of
' the types below.
<XmlChoiceIdentifier("EnumType"), _
XmlElement("Word", GetType(String)), _
XmlElement("Number", GetType(Integer)), _
XmlElement("DecimalNumber", GetType(double))> _
Public MyChoice As Object
' Don't serialize this field. The EnumType field
' contains the enumeration value that corresponds
' to the MyChoice field value.
<XmlIgnore> _
Public EnumType As ItemChoiceType
'The ManyChoices field can contain an array
' of choices. Each choice must be matched to
' an array item in the ChoiceArray field.
<XmlChoiceIdentifier("ChoiceArray"), _
XmlElement("Item", GetType(string)), _
XmlElement("Amount", GetType(Integer)), _
XmlElement("Temp", GetType(double))> _
Public ManyChoices() As Object
' TheChoiceArray field contains the enumeration
' values, one for each item in the ManyChoices array.
<XmlIgnore> _
Public ChoiceArray() As MoreChoices
End Class
<XmlType(IncludeInSchema:=false)> _
Public Enum ItemChoiceType
None
Word
Number
DecimalNumber
End Enum
<XmlType(IncludeInSchema:=false)> _
Public Enum MoreChoices
None
Item
Amount
Temp
End Enum
Public Class Test
Shared Sub Main()
Dim t As Test = New Test()
t.SerializeObject("Choices.xml")
t.DeserializeObject("Choices.xml")
End Sub
private Sub SerializeObject(filename As string)
Dim mySerializer As XmlSerializer = _
New XmlSerializer(GetType(Choices))
Dim writer As TextWriter = New StreamWriter(filename)
Dim myChoices As Choices = New Choices()
' Set the MyChoice field to a string. Set the
' EnumType to Word.
myChoices.MyChoice= "Book"
myChoices.EnumType = ItemChoiceType.Word
' Populate an object array with three items, one
' of each enumeration type. Set the array to the
' ManyChoices field.
Dim strChoices () As Object = New object(){"Food", 5, 98.6}
myChoices.ManyChoices=strChoices
' For each item in the ManyChoices array, add an
' enumeration value.
Dim itmChoices () As MoreChoices = New MoreChoices() _
{MoreChoices.Item, _
MoreChoices.Amount, _
MoreChoices.Temp}
myChoices.ChoiceArray=itmChoices
mySerializer.Serialize(writer, myChoices)
writer.Close()
End Sub
private Sub DeserializeObject(filename As string)
Dim ser As XmlSerializer = New XmlSerializer(GetType(Choices))
' A FileStream is needed to read the XML document.
Dim fs As FileStream = New FileStream(filename, FileMode.Open)
Dim myChoices As Choices = CType(ser.Deserialize(fs), Choices)
fs.Close()
' Disambiguate the MyChoice value Imports the enumeration.
if myChoices.EnumType = ItemChoiceType.Word Then
Console.WriteLine("Word: " & _
myChoices.MyChoice.ToString())
else if myChoices.EnumType = ItemChoiceType.Number Then
Console.WriteLine("Number: " & _
myChoices.MyChoice.ToString())
else if myChoices.EnumType = ItemChoiceType.DecimalNumber Then
Console.WriteLine("DecimalNumber: " & _
myChoices.MyChoice.ToString())
End If
' Disambiguate the ManyChoices values Imports the enumerations.
Dim i As Integer
for i = 0 to myChoices.ManyChoices.Length -1
if myChoices.ChoiceArray(i) = MoreChoices.Item Then
Console.WriteLine("Item: " + _
myChoices.ManyChoices(i).ToString())
else if myChoices.ChoiceArray(i) = MoreChoices.Amount Then
Console.WriteLine("Amount: " + _
myChoices.ManyChoices(i).ToString())
else if (myChoices.ChoiceArray(i) = MoreChoices.Temp)
Console.WriteLine("Temp: " + _
myChoices.ManyChoices(i).ToString())
End If
Next i
End Sub
End Class
Keterangan
Definisi elemen skema XML bernama xsi:choice digunakan untuk menentukan elemen kompleks yang hanya dapat berisi satu anak dalam instans (maxoccurs = 1). Anak itu bisa menjadi salah satu dari beberapa jenis, dan dapat memiliki salah satu dari beberapa nama. Setiap nama dikaitkan dengan jenis tertentu; namun, beberapa nama dapat dikaitkan dengan jenis yang sama. Karena itu, instans elemen seperti itu tidak jelas. Misalnya, pertimbangkan fragmen skema berikut yang mendefinisikan elemen yang tidak jelas bernama MyChoice.
<xsd:complexType name="MyChoice">
<xsd:sequence>
<xsd:choice minOccurs="0" maxOccurs="1">
<xsd:element minOccurs="1" maxOccurs="1" name="ChoiceOne" type="xsd:string" />
<xsd:element minOccurs="1" maxOccurs="1" name="ChoiceTwo" type="xsd:string" />
</xsd:choice>
</xsd:sequence>
</xsd:complexType>
memungkinkan XmlChoiceIdentifierAttribute Anda menetapkan nilai enumerasi khusus untuk setiap instans anggota. Anda harus membuat enumerasi sendiri atau dapat dihasilkan oleh Xml Schema Definition Tool (Xsd.exe). Kode C# berikut menunjukkan bagaimana XmlChoiceIdentifierAttribute diterapkan ke Item bidang; MemberName properti mengidentifikasi bidang yang berisi enumerasi yang lebih lanjut digunakan untuk mendeteksi pilihan.
public class Choices{
[XmlChoiceIdentifier("ItemType")]
[XmlChoiceIdentifier("ChoiceOne")]
[XmlChoiceIdentifier("ChoiceTwo")]
public string MyChoice;
// Do not serialize this next field:
[XmlIgnore]
public ItemChoiceType ItemType;
}
// Do not include this enumeration in the XML schema.
[XmlType(IncludeInSchema = false)]
public enum ItemChoiceType{
ChoiceOne,
ChoiceTwo,
}
Ketika kode ini diberlakukan, Anda dapat menserialisasikan dan mendeserialisasi kelas ini dengan mengatur ItemType bidang ke enumerasi yang sesuai. Misalnya, untuk menserialisasi kelas Choice , kode C# menyerupai yang berikut ini.
Choices mc = new Choices();
mc.MyChoice = "Item Choice One";
mc.ItemType = ItemChoiceType.ChoiceOne;
Saat deserialisasi, kode C# menyerupan berikut:
MyChoice mc = (MyChoice) myXmlSerializer.Deserialize(myReader);
if(mc.ItemType == ItemChoiceType.ChoiceOne)
{
// Handle choice one.
}
if(mc.ItemType == ItemChoiceType.ChoiceTwo)
{
// Handle choice two.
}
if(mc.ItemType != null)
{
throw CreateUnknownTypeException(mc.Item);
}
Ada skenario kedua saat XmlChoiceIdentifierAttribute digunakan. Dalam skema berikut, anggota adalah bidang yang mengembalikan array item (maxOccurs="unbounded"). Array dapat berisi objek pilihan pertama ("D-a-t-a"), dan dari pilihan kedua ("MoreData").
<xsd:complexType name="MyChoice">
<xsd:sequence>
<xsd:choice minOccurs="0" maxOccurs="unbounded">
<xsd:element minOccurs="1" maxOccurs="1" name="D-a-t-a" type="xsd:string" />
<xsd:element minOccurs="1" maxOccurs="1" name="MoreData" type="xsd:string" />
</xsd:choice>
</xsd:sequence>
</xsd:complexType>
Kelas yang dihasilkan kemudian menggunakan bidang untuk mengembalikan array item. Untuk setiap item dalam array, enumerasi yang ItemChoiceType sesuai juga harus ditemukan. Enumerasi yang cocok terkandung dalam array yang dikembalikan oleh ItemsElementName bidang .
public class MyChoice {
[System.Xml.Serialization.XmlElementAttribute("D-a-t-a", typeof(string), IsNullable=false)]
[System.Xml.Serialization.XmlElementAttribute("MoreData", typeof(string), IsNullable=false)]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
public string[] Items;
[System.Xml.Serialization.XmlElementAttribute(IsNullable=false)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemsChoiceType[] ItemsElementName;
}
[System.Xml.Serialization.XmlTypeAttribute(IncludeInSchema=false)]
public enum ItemsChoiceType {
[System.Xml.Serialization.XmlEnumAttribute("D-a-t-a")]
Data,
MoreData,
}
Saat mendeserialisasi objek yang mencakup berbagai pilihan, gunakan struktur kontrol (seperti jika... Kemudian... struktur lainnya) untuk menentukan cara mendeserialisasi nilai tertentu. Dalam struktur kontrol, periksa nilai enumerasi dan deserialisasi nilai yang sesuai.
Konstruktor
| Nama | Deskripsi |
|---|---|
| XmlChoiceIdentifierAttribute() |
Menginisialisasi instans baru dari kelas XmlChoiceIdentifierAttribute. |
| XmlChoiceIdentifierAttribute(String) |
Menginisialisasi instans baru dari kelas XmlChoiceIdentifierAttribute. |
Properti
| Nama | Deskripsi |
|---|---|
| MemberName |
Mendapatkan atau mengatur nama bidang yang mengembalikan enumerasi yang akan digunakan saat mendeteksi jenis. |
| TypeId |
Ketika diimplementasikan dalam kelas turunan, mendapatkan pengidentifikasi unik untuk Attributeini. (Diperoleh dari Attribute) |
Metode
| Nama | Deskripsi |
|---|---|
| Equals(Object) |
Mengembalikan nilai yang menunjukkan apakah instans ini sama dengan objek tertentu. (Diperoleh dari Attribute) |
| GetHashCode() |
Mengembalikan kode hash untuk instans ini. (Diperoleh dari Attribute) |
| GetType() |
Mendapatkan Type instans saat ini. (Diperoleh dari Object) |
| IsDefaultAttribute() |
Ketika ditimpa dalam kelas turunan, menunjukkan apakah nilai instans ini adalah nilai default untuk kelas turunan. (Diperoleh dari Attribute) |
| Match(Object) |
Saat ditimpa dalam kelas turunan, mengembalikan nilai yang menunjukkan apakah instans ini sama dengan objek tertentu. (Diperoleh dari Attribute) |
| MemberwiseClone() |
Membuat salinan dangkal dari Objectsaat ini. (Diperoleh dari Object) |
| ToString() |
Mengembalikan string yang mewakili objek saat ini. (Diperoleh dari Object) |
Implementasi Antarmuka Eksplisit
| Nama | Deskripsi |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Memetakan sekumpulan nama ke sekumpulan pengidentifikasi pengiriman yang sesuai. (Diperoleh dari Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Mengambil informasi jenis untuk objek, yang dapat digunakan untuk mendapatkan informasi jenis untuk antarmuka. (Diperoleh dari Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Mengambil jumlah antarmuka informasi jenis yang disediakan objek (baik 0 atau 1). (Diperoleh dari Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Menyediakan akses ke properti dan metode yang diekspos oleh objek. (Diperoleh dari Attribute) |