Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

static void Main(string[] args) {

BookMark bm1, bm2;

bm1 = new BookMark {

URL = "http://www.amazon.com",

Description = "Amazon.com Web site"

};

bm2 = new BookMark() {

URL = "http://www.wrox.com",

Description = "Wrox.com Web site",

NextURL = null

};

//---link the first BookMark to the next---

bm1.NextURL = bm2;

//========Binary Serialization=========

//---serializing an object graph into a memory stream---

MemoryStream ms = Serialize(bm1);

//---deserializing a memory stream into an object graph---

BookMark bm3 = Deserialize(ms);

//---print out all the bookmarks---

BookMark tempBookMark = bm3;

do {

Console.WriteLine(tempBookMark.URL);

Console.WriteLine(tempBookMark.Description);

Console.WriteLine(tempBookMark.GetDateCreated());

Console.WriteLine(" ");

tempBookMark = tempBookMark.NextURL;

} while (tempBookMark != null);

Console.ReadLine();

}

If the objects are serialized and deserialized correctly, the output is as shown in Figure 11-12.

Figure 1112 But what does the binary stream look like To answer that - фото 175

Figure 11-12

But what does the binary stream look like? To answer that question, take a look at the c:\BookMarks.datfile that you have created in the process. To view the binary file, simply drag and drop the BookMarks.datfile into Visual Studio 2008. You should see something similar to Figure 11-13.

Figure 1113 A few observations are worth noting at this point Private - фото 176

Figure 11-13

A few observations are worth noting at this point:

□ Private variables and properties are all serialized. In binary serialization, both the private variables and properties are serialized. This is known as deep serialization, as opposed to shallow serialization in XML serialization (which only serializes the public variables and properties). The next section discusses XML serialization.

□ Object graphs are serialized and preserved. In this example, two BookMarkobjects are linked, and the serialization process takes care of the relationships between the two objects.

There are times when you do not want to serialize all of the data in your object. If you don't want to persist the date and time that the BookMarkobjects are created, for instance, you can prefix the variable name (that you do not want to serialize) with the [NonSerialized]attribute:

[Serializable]

class BookMark {

[NonSerialized]

private DateTime _dateCreated;

public BookMark() {

_dateCreated = DateTime.Now;

}

public DateTime GetDateCreated() {

return _dateCreated;

}

public string URL { get; set; }

public string Description { get; set; }

public BookMark NextURL { get; set; }

}

The dateCreatedvariable will not be serialized. Figure 11-14 shows that when the dateCreatedvariable is not serialized, its value is set to the default date when the object is deserialized.

Figure 1114 XML Serialization You can also serialize an object into an XML - фото 177

Figure 11-14

XML Serialization

You can also serialize an object into an XML document. There are many advantages to XML serialization. For instance, XML documents are platform-agnostic because they are in plain text format and that makes cross-platform communication quite easy. XML documents are also easy to read and modify, which makes XML a very flexible format for data representation.

The following example illustrates XML serialization and shows you some of its uses.

Defining a Sample Class

Let's define a class so that you can see how XML serialization works. For this example, you define three classes that allow you to store information about a person, such as name, address, and date of birth. Here are the class definitions:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.VisualBasic;

using System.IO;

using System.Xml.Serialization;

using System.Xml;

namespace Serialization {

class Program {

static void Main(string[] args) { }

}

public class Member {

private int age;

public MemberName Name;

public MemberAddress[] Addresses;

public DateTime DOB;

public int currentAge {

get {

//---add a reference to Microsoft.VisualBasic.dll---

age = (int)DateAndTime.DateDiff(

DateInterval.Year, DOB, DateTime.Now,

FirstDayOfWeek.System, FirstWeekOfYear.System);

return age;

}

}

}

public class MemberName {

public string FirstName { get; set; }

public string LastName { get; set; }

}

public class MemberAddress {

public string Line1;

public string Line2;

public string City;

public string Country;

public string Postal;

}

}

The various classes are deliberately designed to illustrate the various aspects of XML serialization. They may not adhere to the best practices for defining classes.

Here are the specifics for the classes:

□ The Memberclass contains both private and public members. It also contains a read-only property.

□ The Memberclass contains a public array containing the address of a Member.

□ The Memberclass contains a variable of Datedata type.

□ The MemberNameclass contains two properties.

□ The MemberAddressclass contains only public members.

Serializing the Class

To serialize a Memberobject into a XML document, you can use the XMLSerializerclass from the System.Xml.Serializationnamespace:

static void Main(string[] args) {}

//========XML Serialization=========

static void XMLSerialize(Member mem) {

StreamWriter sw = new StreamWriter(@"c:\Members.xml");

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x