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

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

Интервал:

Закладка:

Сделать

Title,

Author,

Publisher

};

In this case, the names of the properties will assume the names of the variables, as shown in Figure 4-2.

Figure 42 However you cannot create anonymous types with literals as the - фото 104

Figure 4-2

However, you cannot create anonymous types with literals, as the following example demonstrates:

//---error---

var book1 = new {

"978-0-470-17661-0",

"Professional Windows Vista Gadgets Programming",

"Wei-Meng Lee",

"Wrox"

};

When assigning a literal value to a property in an anonymous type, you must use an identifier, like this:

var book1 = new {

ISBN = "978-0-470-17661-0",

Title="Professional Windows Vista Gadgets Programming",

Author = "Wei-Meng Lee",

Publisher="Wrox"

};

So, how are anonymous types useful for your application? Well, they enable you to shape your data from one type to another. You will look into more about this in Chapter 14, which tackles LINQ.

Class Members

Variables and functions defined in a class are known as a class's members. The Contactclass definition, for instance, has four members that you can access once an object is instantiated:

public class Contact {

public int ID;

public string FirstName;

public string LastName;

public string Email;

}

Members of a class are classified into two types:

Type Description
Data Members that store the data needed by your object so that they can be used by functions to perform their work. For example, you can store a person's name using the FirstName and LastName members.
Function Code blocks within a class. Function members allow the class to perform its work. For example, a function contained within a class (such as the Contact class) can validate the email of a person (stored in the Email member) to see if it is a valid email address.

Data members can be further grouped into instance members and static members.

Instance Members

By default, all data members are instance members unless they are constants or prefixed with the statickeyword (more on this in the next section). The variables defined in the Contactclass are instance members:

public int ID;

public string FirstName;

public string LastName;

public string Email;

Instance members can be accessed only through an instance of a class and each instance of the class (object) has its own copy of the data. Consider the following example:

Contact contact1 = new Contact();

contact1.ID = 12;

contact1.FirstName = "Wei-Meng";

contact1.LastName = "Lee";

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

Contact contact2 = new Contact();

contact2.ID = 35;

contact2.FirstName = "Jason";

contact2.LastName = "Will";

contact2.Email = "JasonWill@company.net";

The objects contact1and contact2each contain information for a different user. Each object maintains its own copy of the ID, FirstName, LastName, and Emaildata members.

Static Members

Static data members belong to the class rather than to each instance of the class. You use the statickeyword to define them. For example, here the Contactclass has a static member named count:

public class Contact {

public static int count;

public int ID;

public string FirstName;

public string LastName;

public string Email;

}

The countstatic member can be used to keep track of the total number of Contactinstances, and thus it should not belong to any instances of the Contactclass but to the class itself.

To use the countstatic variable, access it through the Contactclass:

Contact.count = 4;

Console.WriteLine(Contact.count);

You cannot access it via an instance of the class, such as contact1:

//---error---

contact1.count = 4;

Constants defined within a class are implicitly static, as the following example shows:

public class Contact {

public const ushort MAX_EMAIL = 5;

public static int count;

public int ID;

public string FirstName;

public string LastName;

public string Email;

}

In this case, you can only access the constant through the class name but not set a value to it:

Console.WriteLine(Contact.MAX_EMAIL);

Contact.MAX_EMAIL = 4; //---error---

Access Modifiers

Access modifiers are keywords that you can add to members of a class to restrict their access. Consider the following definition of the Contactclass:

public class Contact {

public const ushort MAX_EMAIL = 5;

public static int count;

public int ID;

public string FirstName;

public string LastName;

private string _Email;

}

Unlike the rest of the data members, the _Emaildata member has been defined with the privatekeyword. The publickeyword indicates that the data member is visible outside the class, while the privatekeyword indicates that the data member is only visible within the class.

By convention, you can denote a private variable by beginning its name with the underscore (_) character. This is recommended, but not mandatory.

For example, you can access the FirstNamedata member through an instance of the Contactclass:

//---this is OK---

contact1.FirstName = "Wei-Meng";

But you cannot access the _Emaildata member outside the class, as the following statement demonstrates:

//---error: _Email is inaccessible---

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

C# has four access modifiers — private, public, protected, and internal.The last two are discussed with inheritance in the next chapter.

If a data member is declared without the publickeyword, its scope (or access) is privateby default. So, _Emailcan also be declared like this:

public class Contact {

public const ushort MAX_EMAIL = 5;

public static int count;

public int ID;

public string FirstName;

public string LastName;

string _Email;

}

Function Members

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

Интервал:

Закладка:

Сделать

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

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


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

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

x