我有一個數組,其索引映射回Enum
值。我想使用C#Xml序列化庫來序列化這個數組。但是,我希望每個Xml節點都能說出它所代表的Enum類型的名稱。我怎樣才能做到這一點?命名數組中的每個元素
例子:
public class NumberOfEmployees
{
public enum EmployeeType { Lawyer, Doctor, Engineer };
public int[] NumEmployees { get; set; }
// Constructor initializes array to size of "EmployeeType"
public NumberOfEmployees()
{
int size = Enum.GetValues(typeof(EmployeeType)).Length;
this.NumEmployees = new int[size];
}
}
Main()
{
NumberOfEmployees numEmployees = new NumberOfEmployees();
// Add doctors, lawyers, engineers, etc...
// numEmployees.NumEmployees[(int)NumberOfEmployees.Lawyer] = 3;
// numEmployees.NumEmployees[(int)NumberOfEmployees.Doctor] = 2;
// numEmployees.NumEmployees[(int)NumberOfEmployees.Engineer] = 1;
// Serialize to "file"
FileStream fs = new FileStream(file, FileMode.OpenOrCreate);
XmlSerializer xml = new XmlSerializer(typeof(NumberOfEmployees));
xml.Serialize(fs, numEmployees);
fs.Close();
}
最終的結果是XML,看起來是這樣的:
<NumEmployees>
<int>3</int>
<int>2</int>
<int>1</int>
</NumEmployees>
但我想要的是:
<NumEmployees>
<Lawyer>3</Lawyer>
<Doctor>2</Doctor>
<Engineer>1</Engineer>
</NumEmployees>
我不能存儲的每個號碼分開 - 它必須是一個數組。
謝謝。