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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

public class AddressBook {

public void AddContact(Contact c) {

Console.WriteLine(c.ID);

Console.WriteLine(c.FirstName);

Console.WriteLine(c.LastName);

Console.WriteLine(c.Email);

//---other implementations here---

//...

}

}

The AddContact()method takes in a Contactobject and prints out the details of the contact. Suppose that the Contactclass has a AddToAddressBook()method that takes in an AddressBookobject. This method adds the Contactobject into the AddressBookobject:

public class Contact {

public int ID;

public string FirstName;

public string LastName;

public string Email;

public void AddToAddressBook(AddressBook addBook) {

addBook.AddContact(this);

}

}

In this case, you use the thiskeyword to pass in the current instance of the Contactobject into the AddressBookobject. To test out that code, use the following statements:

Contact contact1 = new Contact();

contact1.ID = 12;

contact1.FirstName = "Wei-Meng";

contact1.LastName = "Lee";

contact1.Email = "weimenglee@learn2develop.net";

AddressBook addBook1 = new AddressBook();

contact1.AddToAddressBook(addBook1);

Properties

Properties are function members that provide an easy way to read or write the values of private data members. Recall the Contactclass defined earlier:

public class Contact {

public int ID;

public string FirstName;

public string LastName;

public string Email;

}

You've seen that you can create a Contactobject and set its public data members ( ID, FirstName, LastName, and Email) directly, like this:

Contact c = new Contact();

c.ID = 1234;

c.FirstName = "Wei-Meng";

c.LastName = "Lee";

c.Email = "weimenglee@learn2develop.net";

However, if the IDof a person has a valid range of values — such as from 1 to 9999 — the following value of 12345 would still be assigned to the ID data member:

c.ID = 12345;

Technically, the assignment is valid, but logically it should not be allowed — the number assigned is beyond the range of values permitted for ID. Of course you can perform some checks before assigning a value to the ID member, but doing so violates the spirit of encapsulation in object- oriented programming — the checks should be done within the class.

A solution to this is to use properties.

The Contact class can be rewritten as follows with its data members converted to properties:

public class Contact {

int _ID;

string _FirstName, _LastName, _Email;

public int ID {

get {

return _ID;

}

set {

_ID = value;

}

}

public string FirstName {

get {

return _FirstName;

}

set {

_FirstName = value;

}

}

public string LastName {

get {

return _LastName;

}

set {

_LastName = value;

}

}

public string Email {

get {

return _Email;

}

set {

_Email = value;

}

}

}

Note that the public members ( ID, FirstName, LastName, and Email) have been replaced by properties with the setand getaccessors.

The setaccessor sets the value of a property. Using this example, you can instantiate a Contactclass and then set the value of the IDproperty, like this:

Contact c = new Contact();

c.ID = 1234;

In this case, the setaccessor is invoked:

public int ID {

get {

return _ID;

}

set {

_ID = value;

}

}

The valuekeyword contains the value that is being assigned by the setaccessor. You normally assign the value of a property to a private member so that it is not visible to code outside the class, which in this case is _ID.

When you retrieve the value of a property, the getaccessor is invoked:

public int ID {

get {

return _ID;

}

set {

_ID = value;

}

}

The following statement shows an example of retrieving the value of a property:

Console.WriteLine(c.ID); //---prints out 1234---

The really useful part of properties is the capability for you to perform checking on the value assigned. For example, before the IDproperty is set, you want to make sure that the value is between 1 and 9999, so you perform the check at the set accessor, like this:

public int ID {

get {

return _ID;

}

set {

if (value > 0 && value <= 9999) {

_ID = value;

} else {

_ID = 0;

};

}

}

Using properties, you can now prevent users from setting invalid values.

Read-Only and Write-Only Properties

When a property definition contains the getand setaccessors, that property can be read as well as written. To make a property read-only, you simply leave out the setaccessor, like this:

public int ID {

get {

return _ID;

}

}

You can now read but not write values into the IDproperty:

Console.WriteLine(c1.ID); //---OK---

c1.ID = 1234; //---Error---

Likewise, to make a property write-only, simply leave out the getaccessor:

public int ID {

set {

_ID = value;

}

}

You can now write but not read from the IDproperty:

Console.WriteLine(c1.ID); //---Error---

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

Интервал:

Закладка:

Сделать

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

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


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

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

x