Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

the program should proceed with the font−changing process.

Trick If you like, you can use this approach of accessing the result of the ShowDialog() method to write your file access code without using the file dialog’s methods. I will soon show you this second technique of file dialog access in the section "Storing Entire Objects with Object Serialization."

Using the Color Dialog Control

The code for the color−changing menu items is very similar to the code for changing the font:

private void mnuForeground_Click(object sender, System.EventArgs e) {

if (colorDialog1.ShowDialog() != DialogResult.Cancel){ txtEdit.ForeColor = colorDialog1.Color;

} // end if

}

private void mnuBackground_Click(object sender, System.EventArgs e) {

if (colorDialog1.ShowDialog() != DialogResult.Cancel){ txtEdit.BackColor = colorDialog1.Color;

} // end if

}// end

The event handlers are strikingly similar. Both display colorDialog1 and copy the Color property from that dialog to the text box if the user didn’t cancel. However, the mnuForeground event copies the color to the text box’s ForeColor property, and the mnuBackground event copies the color to the BackColor property of the text box.

Trick If I had insisted on using the event technique with the color dialog, I would have a problem because two different methods need access to the same dialog. Either I would need two color dialogs (which would be wasteful of system resources), or I would have to determine in the event code which method called the dialog (which is possible with the sender parameter, but somewhat clumsy). The approach described in this section seems more appropriate for this particular situation.

Storing Entire Objects with Serialization

Text−based files are very easy to work with as long as the information is not long or complex. However, many applications require manipulation of more complex data. In an object−oriented language such as C#, it makes sense to be able to save and load objects directly, because objects are the primary unit in an OOP program. C# provides a mechanism for easily storing and loading classes—object serialization. In general, you can store any kind of information you can put in a class, and you can easily retrieve the information.

Exploring the Serialization Demo Program

An example will help explain the concept of object serialization. The Serialization Demo program featured in Figure 9.18 illustrates object serialization at work. All the data for a contact is stored in a special class named Contact. The Contact class is stored on the file system and can be loaded from the system. The Save button contains code to send the data to a file, and the Load button retrieves the data from the file.

256

Figure 9.18: The user can enter data into text boxes.

Creating the Contact Class

The Contact class is a very simple class containing three properties. I kept the class simple for demonstration purposes, but any class, even one with methods and events, can be serialized. As you examine the code, you will see only one new element in the class definition:

using System;

namespace SerDemo {

///<summary>

///The Serializable contact class

///</summary>

[Serializable]

public class Contact { private string name = ""; private string address = ""; private string phone = "";

//properties

public string Name { set {

name = value;

}// end set get {

return name;

}// end get

}// end name prop

public string Address { set {

address = value;

}// end set get {

return address;

}// end get

}// end address prop

public string Phone { set {

phone = value;

}// end set get {

return phone;

}// end get

}// end phone prop

public Contact() {

//no constructor necessary } // end constructor

257

} // end class def

}// end namespace

The only new element is the [Serializable] attribute. Attributes are special directives to the compiler. The Serializable attribute indicates that the current class can be serialized to the file system.

Referencing the Serializable Namespace

A class that will load and store serialized objects needs to refer to the IO namespace and a special serialization namespace. I added the following two using statements to the normal array of references at the beginning of SerDemo:

using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

System.Runtime.Serialization.Formatters.Binary is a namespace containing classes for storing and retrieving classes.

In the Real World

C# supports two types of serialization. The serialization technique described in this chapter is called binary serialization. Binary serialization stores data in efficient binary files, but these files are not readable in a text editor and are clumsy to transport across the Internet. The .NET framework purports to support the SOAP (Simple Object Access Protocol), also. This converts an object to an XML format that can be read in a text editor and is easily shared on multiple operating systems. Unfortunately, the SOAP namespace was not included in the preliminary version of C# I used when preparing this book. However, you will find that the techniques for storing a file using SOAP are almost completely identical to the technique described in this chapter for using the binary protocol, even though the underlying technologies are different. If you learn how to do binary serialization, switching to SOAP will be no big deal. Again, encapsulation and polymorphism save the day.

Storing a Class

All the code that manages the storage of the class occurs in the btnStore_Click() method:

private void btnSave_Click(object sender, System.EventArgs e) { thePerson.Name = txtName.Text;

thePerson.Address = txtAddress.Text; thePerson.Phone = txtPhone.Text;

FileStream s;

s = new FileStream("Contacts.bin", FileMode.Create, FileAccess.Write);

BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(s, thePerson);

s.Close();

} // end btnSave_Click

The first part of the method copies the parts of the contact from the text boxes to properties of the Contact class. The program then creates a FileStream object. The FileStream is a basic type of stream that can be used for any kind of data, so it is an ideal choice for a serialized class. Because StreamReader is used only to input text and StreamWriter is used only for text input, it was

258

Соседние файлы в предмете Программирование на C++