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

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

Интервал:

Закладка:

Сделать
Constructors

Instead of initializing the individual properties of an object after it has been instantiated, it is sometimes useful to initialize them at the time of instantiation. Constructors are class methods that are executed when an object is instantiated.

Using the Contactclass as the example, the following constructor initializes the ID property to 9999 every time an object is instantiated:

public class Contact {

int _ID;

public int ID {

get {

return _ID;

}

set {

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

_ID = value;

} else {

_ID = 0;

};

}

}

public string FirstName { get; set; }

public string LastName { get; set; }

public string Email { get; set; }

public Contact() {

this.ID = 9999;

}

}

The following statement proves that the constructor is called:

Contact c = new Contact();

//---prints out 9999---

Console.WriteLine(c.ID);

Constructors have the same name as the class and they do not return any values. In this example, the constructor is defined without any parameters. A constructor that takes in no parameters is called a default constructor. It is invoked when you instantiate an object without any arguments, like this:

Contact c = new Contact();

If you do not define a default constructor in your class, an implicit default constructor is automatically created by the compiler.

You can have as many constructors as you need to, as long as each constructor's signature (parameters) is different. Let's now add two more constructors to the Contactclass:

public class Contact {

//...

public Contact() {

this.ID = 9999;

}

public Contact(int ID) {

this.ID = ID;

}

public Contact(int ID, string FirstName, string LastName, string Email) {

this.ID = ID;

this.FirstName = FirstName;

this.LastName = LastName;

this.Email = Email;

}

}

When you have multiple methods (constructors in this case) with the same name but different signatures, the methods are known as overloaded. IntelliSense will show the different signatures available when you try to instantiate a Contactobject (see Figure 4-3).

Figure 43 You can create instances of the Contact class using the different - фото 105

Figure 4-3

You can create instances of the Contact class using the different constructors:

//---first constructor is called---

Contact c1 = new Contact();

//---second constructor is called---

Contact c2 = new Contact(1234);

//---third constructor is called---

Contact c3 = new Contact(1234, "Wei-Meng", "Lee", "weimenglee@learn2develop.net");

Constructor Chaining

Suppose that the Contactclass has the following four constructors:

public class Contact {

//...

public Contact() {

this.ID = 9999;

}

public Contact(int ID) {

this.ID = ID;

}

public Contact(int ID, string FirstName, string LastName) {

this.ID = ID;

this.FirstName = FirstName;

this.LastName = LastName;

}

public Contact(int ID, string FirstName, string LastName, string Email) {

this.ID = ID;

this.FirstName = FirstName;

this.LastName = LastName;

this.Email = Email;

}

}

Instead of setting the properties individually in each constructor, each constructor itself sets some of the properties for other constructors. A more efficient way would be for some constructors to call the other constructors to set some of the properties. That would prevent a duplication of code that does the same thing. The Contactclass could be rewritten like this:

public class Contact {

//...

//---first constructor---

public Contact() {

this.ID = 9999;

}

//---second constructor---

public Contact(int ID) {

this.ID = ID;

}

//---third constructor---

public Contact(int ID, string FirstName, string LastName) :

this(ID) {

this.FirstName = FirstName;

this.LastName = LastName;

}

//---fourth constructor---

public Contact(int ID, string FirstName, string LastName, string Email) :

this(ID, FirstName, LastName) {

this.Email = Email;

}

}

In this case, the fourth constructor is calling the third constructor using the thiskeyword. In addition, it is also passing in the arguments required by the third constructor. The third constructor in turn calls the second constructor. This process of one constructor calling another is call constructor chaining.

To prove that constructor chaining works, use the following statements:

Contact c1 = new Contact(1234, "Wei-Meng", "Lee", "weimenglee@learn2develop.net");

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

Console.WriteLine(c1.FirstName); //---Wei-Meng---

Console.WriteLine(c1.LastName); //---Lee---

Console.WriteLine(c1.Email); //---weimenglee@learn2develop.net---

To understand the sequence of the constructors that are called, insert the following highlighted statements:

class Contact {

//...

//---first constructor---

public Contact() {

this.ID = 9999;

Console.WriteLine("First constructor");

}

//---second constructor---

public Contact(int ID) {

this.ID = ID;

Console.WriteLine("Second constructor");

}

//---third constructor---

public Contact(int ID, string FirstName, string LastName) :

this(ID) {

this.FirstName = FirstName;

this.LastName = LastName;

Console.WriteLine("Third constructor");

}

//---fourth constructor---

public Contact(int ID, string FirstName, string LastName, string Email) :

this(ID, FirstName, LastName) {

this.Email = Email;

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

Интервал:

Закладка:

Сделать

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

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


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

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

x