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

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

Интервал:

Закладка:

Сделать

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

You can also restrict the visibility of the getand setaccessors. For example, the setaccessor of a public property could be set to privateto allow only members of the class to call the setaccessor, but any class could call the getaccessor. The following example demonstrates this:

public int ID {

get {

return _ID;

}

private set {

_ID = value;

}

}

In this code, the setaccessor of the ID property is prefixed with the privatekeyword to restrict its visibility. That means that you now cannot assign a value to the IDproperty but you can access it:

c.ID = 1234; //---error---

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

You can, however, access the IDproperty anywhere within the Contactclass itself, such as in the Emailproperty:

public string Email {

get {

//...

this.ID = 1234;

//...

}

//...

}

Partial Methods (C# 3.0)

Earlier on, you saw that a class definition can be split into one or more class definitions. In C# 3.0, this concept is extended to methods — you can now have partial methods. To see how partial methods works, consider the Contactpartial class:

public partial class Contact {

//...

private string _Email;

public string Email {

get {

return _Email;

}

set {

_Email = value;

}

}

}

Suppose you that want to allow users of this partial class to optionally log the email address of each contact when its Emailproperty is set. In that case, you can define a partial method — LogEmail()in this example — like this:

public partial class Contact {

//...

}

public partial class Contact {

//...

private string _Email;

public string Email {

get {

return _Email;

}

set {

_Email = value;

LogEmail();

}

}

//---partial methods are private---

partial void LogEmail();

}

The partial method LogEmail()is called when a contact's email is set via the Emailproperty. Note that this method has no implementation. Where is the implementation? It can optionally be implemented in another partial class. For example, if another developer decides to use the Contactpartial class, he or she can define another partial class containing the implementation for the LogEmail()method:

public partial class Contact {

partial void LogEmail() {

//---code to send email to contact---

Console.WriteLine("Email set: {0}", _Email);

}

}

So when you now instantiate an instance of the Contactclass, you can set its Emailproperty as follows and a line will be printed in the output window:

Contact contact1 = new Contact();

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

What if there is no implementation of the LogEmail()method? Well, in that case the compiler simply removes the call to this method, and there is no change to your code.

Partial methods are useful when you are dealing with generated code. For example, suppose that the Contactclass is generated by a code generator. The signature of the partial method is defined in the class, but it is totally up to you to decide if you need to implement it.

A partial method must be declared within a partial class or partial struct.

Partial methods must adhere to the following rules:

□ Must begin with the partialkeyword and the method must return void

□ Can have refbut not outparameters

□ They are implicitly private, and therefore they cannot be virtual (virtual methods are discussed in the next chapter)

□ Parameter and type parameter names do not have to be the same in the implementing and defining declarations

Automatic Properties (C# 3.0)

In the Contact classdefined in the previous section, apart from the IDproperty, the properties are actually not doing much except assigning their values to private members:

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;

}

}

In other words, you are not actually doing any checking before the values are assigned. In C# 3.0, you can shorten those properties that have no filtering (checking) rules by using a feature known as automatic properties. The Contactclass can be rewritten as:

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;}

}

Now there's no need for you to define private members to store the values of the properties. Instead, you just need to use the getand setkeywords, and the compiler will automatically create the private members in which to store the properties values. If you decide to add filtering rules to the properties later, you can simply implement the set andget accessor of each property.

To restrict the visibility of the getand setaccessor when using the automatic properties feature, you simply prefix the get or set accessor with the privatekeyword, like this:

public string FirstName {get; private set;}

This statement sets the FirstNameproperty as read-only.

You might be tempted to directly convert these properties ( FirstName, LastName, and Email) into public data members. But if you did that and then later decided to convert these public members into properties, you would need to recompile all of the assemblies that were compiled against the old class.

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

Интервал:

Закладка:

Сделать

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

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


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

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

x