c 1 introduction to programming and the c language

c 1 introduction to programming and the c language


DisciplinaFísica Básica I826 materiais10.232 seguidores
Pré-visualização50 páginas
}
private static void Show(List<Person> list)
{
for (int i = 0; i < list.Count; ++i) Console.WriteLine(list[i]);
}
private static void Serialiser(List<Person> list)
{
BinaryFormatter bf = new BinaryFormatter();
FileStream stream = File.Create(&quot;F:\\Temp\\List.dat&quot;);
bf.Serialize(stream, list);
stream.Close();
}
private static List<Person> DeSerialiser()
{
List<Person> list = null;
try
{
BinaryFormatter bf = new BinaryFormatter();
FileStream stream = File.OpenRead(&quot;F:\\Temp\\List.dat&quot;);
list = (List<Person>)bf.Deserialize(stream);
stream.Close();
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
251 
Object serialization
}
catch
{
}
return list;
}
}
}
Explanation
There is really not much to explain, and the only thing to point out is that the various collection classes 
generally are Serializable, and a list of Serializable objects (objects of the type Person) can therefore 
immediately be serialized.
Download free eBooks at bookboon.com
Click on the ad to read more
C# 1 Introduction to programming and the C# language 
252 
User defined serialization
32 User defined serialization
The serialization process as described is generally seen by the programmer simple and there is rarely 
reason to do more than are described above. However, there is the possibility to intervene in the process 
if there are special needs.
As an example one can imagine that a class has variables that you, for one reason or another, do not 
want to be serialized. Below is a class Employee which inherits the class Person and expands it with two 
variables, the first being the date of employment, while the second is the current year. The class has a 
method Seniority(), which \u2013 somewhat simplified \u2013 returns an employee\u2019s seniority as the number of 
years between year of employment and the current year. The class is Serializable, but it makes no sense 
to serialize the variable year, since its value depends on when the program is run. However, one can 
mark a variable with the attribute NonSerialized, which says that it should not be serialized.
[Serializable]
public class Employee : Person
{
private DateTime date;
[NonSerialized]
protected int year = DateTime.Now.Year;
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
253 
User defined serialization
[OnDeserialized]
public void InitYear(StreamingContext context)
{
year = DateTime.Now.Year;
}
public Employee(string name, string position, DateTime date)
: base(name, position)
{
this.date = date;
}
public int Seniority()
{
return year - date.Year;
}
}
It does provide a small problem with getting this variable initialized when an object is deserialized. This is 
handled by the method InitYear(), which is a method which is performed after the deserialization process. 
Here you must note the attribute, which tells that it is a method to be performed after deserialization 
and the method\u2019s signature and the parameter type StreamingContext that is an enum that is rarely used 
for anything.
The following program serializes and deserializes an Employee object:
namespace Exam66
{
class Program
{
static void Main(string[] args)
{
Save();
Load();
}
public static void Save()
{
Employee employee = new Employee(&quot;Karlo Andersen&quot;, &quot;Tater&quot;,
 new DateTime(2002, 03, 15));
Serialiser(employee);
}
public static void Load()
{
Employee employee = DeSerialiser();
if (employee != null) Console.WriteLine(employee);
}
private static void Serialiser(Employee employee)
{
BinaryFormatter bf = new BinaryFormatter();
FileStream stream = File.Create(&quot;Employee.dat&quot;);
bf.Serialize(stream, employee, null);
stream.Close();
}
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
254 
User defined serialization
private static Employee DeSerialiser()
{
Employee employee = null;
try
{
BinaryFormatter bf = new BinaryFormatter();
FileStream stream = File.OpenRead(&quot;Employee.dat&quot;);
employee = (Employee)bf.Deserialize(stream);
stream.Close();
}
catch
{
}
return employee;
}
}
}
There are other corresponding attributes that can be used to decorate the methods of performing a 
similar signature:
\u2022	 OnDeserializing to provide a method which is carried out before the deserialization process
\u2022	 OnSerialized specifies a method that is performed immediately after the serialization process
\u2022	 OnSerializing which specifies a method being carried out before the serialization process
In addition to that as illustrated above where you can define methods which are performed before and 
after, respectively serialization and deserialization, it is also possible to directly control the process in 
terms of how data is serialized and deserialized. The principle is illustrated by the following class that 
represents a member who is a specialization of the class Person:
[Serializable]
public class Member : Person, ISerializable
{
private string ssn;
private string phone;
private string email;
public Member(string ssn, string name, string position, string
phone, string email)
: base(name, position)
{
this.ssn = ssn;
this.phone = phone;
this.email = email;
}
public Member(SerializationInfo info, StreamingContext context)
{
ssn = info.GetString(&quot;ssn&quot;);
Name = info.GetString(&quot;name&quot;);
Position = info.GetString(&quot;position&quot;);
phone = info.GetString(&quot;phone&quot;);
email = info.GetString(&quot;email&quot;).ToLower();
}
Download free eBooks at bookboon.com
Click on the ad to read more
C# 1 Introduction to programming and the C# language 
255 
User defined serialization
public string Ssn
{
get { return ssn; }
set { ssn = value; }
}
public string Phone
{
get { return phone; }
set { phone = value; }
}
public string Email
{
get { return email; }
set { email = value; }
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(&quot;ssn&quot;, FormatSsn());
info.AddValue(&quot;name&quot;, Name);
info.AddValue(&quot;position&quot;, Position);
info.AddValue(&quot;phone&quot;, FormatPhone());
info.AddValue(&quot;email&quot;, email.ToUpper());
}
private string Format Ssn()
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < ssn.Length; ++i)
if (ssn[i] >= '0' && ssn[i] <= '9')
{
your chance 
to change 
the world
Here at Ericsson we have a deep rooted belief that 
the innovations we make on a daily basis can have a 
profound effect on making the world a better place 
for people, business and society. Join us.
In Germany we are especially looking for graduates 
as Integration Engineers for 
\u2022	 Radio Access and IP Networks
\u2022	 IMS and IPTV
We are looking forward to getting your application!
To apply and for all current job openings please visit 
our web page: www.ericsson.com/careers
Download free eBooks at bookboon.com
C# 1 Introduction to programming and the C# language 
256 
User defined serialization
builder.Append(ssn[i]);
if (builder.Length == 6) builder.Append('-');
}
return builder.ToString();
}
private string FormatPhone()
{
StringBuilder builder = new StringBuilder();
for (int i = 0, j = 0; i < phone.Length; ++i)
if (phone[i] >= '0' && phone[i] <= '9')
{
builder.Append(phone[i]);
++j;
if (j == 2)
{
builder.Append(' ');
j = 0;
}
}
return builder.ToString();
}
public override string ToString()
{
return string.Format(&quot;{0}\n{1}\n{2}\n{3}&quot;, ssn, base.ToString(), phone, email);
}
}
It is important to note that the class implements the interface ISerializable, which is an interface that 
defines a single method: GetObjectData(). If a serializable class implements this interface, a formatter 
will call the method GetObjectData(), and here you can so in