2
0

icollection.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4. using System.Xml.Serialization;
  5. public class Test
  6. {
  7. public static void Main()
  8. {
  9. Test t=new Test();
  10. t.Create("icollection.xml");
  11. t.Read("icollection.xml");
  12. }
  13. private void Create(string filename)
  14. {
  15. Employees emps=new Employees();
  16. /* Note that only the collection is serialized, not
  17. * the CollectionName or any other public property of
  18. * the class.
  19. */
  20. emps.CollectionName="Employees";
  21. Employee john100=new Employee("John", "100xxx");
  22. emps.Add(john100);
  23. XmlSerializer ser=new XmlSerializer(typeof(Employees));
  24. TextWriter writer=new StreamWriter(filename);
  25. ser.Serialize(writer, emps);
  26. writer.Close();
  27. }
  28. private void Read(string filename)
  29. {
  30. XmlSerializer ser=new XmlSerializer(typeof(Employees));
  31. FileStream fs=new FileStream(filename, FileMode.Open);
  32. Employees emps;
  33. emps=(Employees)ser.Deserialize(fs);
  34. fs.Close();
  35. /* Not serialized! */
  36. Console.WriteLine("Collection name: "+emps.CollectionName);
  37. foreach(Employee emp in emps)
  38. {
  39. Console.WriteLine("Employee name: "+emp.EmpName);
  40. Console.WriteLine("Employee ID: "+emp.EmpID);
  41. }
  42. }
  43. }
  44. public class Employees:ICollection
  45. {
  46. public string CollectionName;
  47. private ArrayList empArray=new ArrayList();
  48. public Employee this[int index]
  49. {
  50. get {
  51. return((Employee)empArray[index]);
  52. }
  53. }
  54. public void CopyTo(Array a, int index)
  55. {
  56. empArray.CopyTo(a, index);
  57. }
  58. public int Count
  59. {
  60. get {
  61. return(empArray.Count);
  62. }
  63. }
  64. public object SyncRoot
  65. {
  66. get {
  67. return(this);
  68. }
  69. }
  70. public bool IsSynchronized
  71. {
  72. get {
  73. return(false);
  74. }
  75. }
  76. public IEnumerator GetEnumerator()
  77. {
  78. return(empArray.GetEnumerator());
  79. }
  80. public void Add(Employee newEmployee)
  81. {
  82. empArray.Add(newEmployee);
  83. }
  84. }
  85. public class Employee
  86. {
  87. public string EmpName;
  88. public string EmpID;
  89. public Employee()
  90. {}
  91. public Employee(string empName, string empID)
  92. {
  93. EmpName=empName;
  94. EmpID=empID;
  95. }
  96. }