Приклад серіалізації колекції ArrayList

Наведу приклад серіалізації колекції ArrayList з власних елементів MyElementClass:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
 
class Program
 {
  
static void Main(string[] args)
   {
    
ArrayList al = new ArrayList();
     XmlSerializer serializer=
new XmlSerializer(typeof(ArrayList),new Type[] {typeof (MyElementClass )});
     al.Add(
new MyElementClass());
     al.Add (
new MyElementClass (2,"AAA"));
    
Console.WriteLine("Writing With Stream");
    
try
    
{
       
Stream writer = new FileStream("C:\A.XML", FileMode.Create);
       
serializer.Serialize(writer, al);
       
writer.Close();
     
}
     
catch (Exception ex)
     
{
       
Console.WriteLine(ex.Message );
     
}
 
}
}

Сам елемент є клас:

using

System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
 
public class MyElementClass: IComparable
  {
   
public int ID;
   
public string Name;
   
public MyElementClass()
    {
      ID = 1;
      Name =
"ABC";
    }
   
public MyElementClass(int id, string name)
    {
      ID = id;
      Name = name;
    }
   
public int CompareTo(object obj)
    {
      
if (obj is MyElementClass)
        {
           MyElementClass otherElement = (MyElementClass)obj;
          
return this.ID.CompareTo (otherElement.ID);
        }
      
else
       
{
         
throw new ArgumentException("object is not a MyElement");
        }
   }
 }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s