Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Serialize an Array with ISerializable? 1

Status
Not open for further replies.

huckfinn19

Programmer
May 16, 2003
90
CA
Hi!

I am trying to serialize a class that contains a list of objects. Here's the situation:

Code:
[Serializable()]
class A: ISerializable{
    ArrayList m_aList;//Contains objects of type B
    //... methods to fill array with object B

    public A(){}

    public A(SerializationInfo info, StreamingContext ctxt)
    {
        //***Need to serialize the list of objects B here!!
    }
    public void GetObjectData(SerializationInfo info, 
                              StreamingContext ctxt) 
    {
        //***How can I unserialize the list here?
    }
}

class B{
    string m_sName;
    public string Name{ 
        get{return m_sName;} 
        set{m_sName = value;}
    }
    public B(){}
}

So I need a way to serialize and unserialize the list of objects B contained in A. Normally, B would be a more complicated class with the serialization capabilities too.

Thanks!

Huck
 
Here is an example that could help you.
Class B is derived from A and a class D has an arraylist of B object.
[Serializable()]
public class A
{

private object csv = "a,b,c,d";

public object[] Items
{
get{ return csv.ToString().Split(new char[] {','}); }
}

}
[Serializable()]
public class B:A
{
public string member1;
public double member2;
public B()
{
}
public B(string s, double d)
{
member1=s;
member2=d;
}
}
[Serializable()]
public class D
{
public ArrayList arrList;
public D()
{
arrList=new ArrayList();
B b1=new B("one",1.0);
arrList.Add(b1);
B b2=new B("two",2.0);
arrList.Add(b2);
B b3=new B("three",3.0);
arrList.Add(b3);
}

}

Code:
Here is how to persist a D object and restore it later.
[code]
public void SerializeTest()  
{

	D obj = new D();

	//Opens a file and serializes the object into it in binary format.
	Stream stream = File.Open("data.xml", FileMode.Create);
	SoapFormatter formatter = new SoapFormatter();

	//BinaryFormatter formatter = new BinaryFormatter();

	formatter.Serialize(stream, obj);
	stream.Close();

	//Empties obj.
	obj = null;

	//Opens file "data.xml" and deserializes the D object from it.
	stream = File.Open("data.xml", FileMode.Open);
	formatter = new SoapFormatter();

	//formatter = new BinaryFormatter();

	D objrestored = (ClassD)formatter.Deserialize(stream);
	stream.Close();
	objrestored=null;
}
To exclude a member from the serialize list , apply the NonSerialized attribute:
[NonSerialized()] public string member1;
obislavu
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top