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

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

Интервал:

Закладка:

Сделать
Figure 240 Your code now looks like this private void Form1Loadobject - фото 44

Figure 2-40

Your code now looks like this:

private void Form1_Load(object sender, EventArgs e) {

try {

int num1 = 5;

int num2 = 0;

int result = num1 / num2;

} catch (Exception) {

throw;

}

}

IntelliSense

IntelliSense is one of the most useful tools in Visual Studio 2008. IntelliSense automatically detects the properties, methods, events, and so forth of an object as you type in the code editor. You do not need to remember the exact member names of an object because IntelliSense helps you by dynamically providing you with a list of relevant members as you enter your code.

For example, when you type the word Consolein the code editor followed by the ., IntelliSense displays a list of relevant members pertaining to the Consoleclass (see Figure 2-41).

Figure 241 When you have selected the member you want to use press the Tab - фото 45

Figure 2-41

When you have selected the member you want to use, press the Tab key and IntelliSense will insert the member into your code.

IntelliSense in Visual Studio 2008 has some great enhancements. For example, the IntelliSense dropdown list often obscures the code that is behind when it pops up. You can now make the dropdown list disappear momentarily by pressing the Control key. Figure 2-42 shows the IntelliSense dropdown list blocking the code behind it (top) and having it be translucent by pressing the Control key (bottom).

Figure 242 You can also use IntelliSense to tidy up the namespaces at the top - фото 46

Figure 2-42

You can also use IntelliSense to tidy up the namespaces at the top of your code. For example, you often import a lot of namespaces at the beginning of your code and some of them might not ever be used by your application. In Visual Studio 2008, you can select the namespaces, right-click, and select Organize Usings (see Figure 2-43).

Figure 243 Then you can choose to Remove all unused using statements Sort - фото 47

Figure 2-43

Then you can choose to:

□ Remove all unused using statements

□ Sort the using statements alphabetically

□ Remove all unused using statements and sort the remaining namespace alphabetically

Refactoring Support

Another useful feature available in Visual Studio 2008 is code refactoring. Even though the term may sound unfamiliar, many of you have actually used it. In a nutshell, code refactoring means restructuring your code so that the original intention of the code is preserved. For example, you may rename a variable so that it better reflects its usage. In that case, the entire application that uses the variable needs to be updated with the new name. Another example of code refactoring is extracting a block of code and placing it into a function for more efficient code reuse. In either case, you would need to put in significant amount of effort to ensure that you do not inadvertently inject errors into the modified code. In Visual Studio 2008, you can perform code refactoring easily. The following sections explain how to use this feature.

Rename

Renaming variables is a common programming task. However, if you are not careful, you may inadvertently rename the wrong variable (most people use the find-and-replace feature available in the IDE, which is susceptible to wrongly renaming variables). In C# refactoring, you can rename a variable by selecting it, right-clicking, and choosing Refactoring→Rename (see Figure 2-44).

Figure 244 You are prompted for a new name see Figure 245 Enter a new - фото 48

Figure 2-44

You are prompted for a new name (see Figure 2-45). Enter a new name, and click OK.

Figure 245 You can preview the change see Figure 246 before it is applied - фото 49

Figure 2-45

You can preview the change (see Figure 2-46) before it is applied to your code.

Figure 246 Click the Apply button to change the variable name Extract Method - фото 50

Figure 2-46

Click the Apply button to change the variable name.

Extract Method

Very often, you write repetitive code within your application. Consider the following example:

private void Form1_Load(object sender, EventArgs e) {

int num = 10, sum = 0;

for (int i = 1; i <= num; i++) {

sum += i;

}

}

Here, you are summing up all the numbers from 1 to num, a common operation. It would be better for you to package this block of code into a function. So, highlight the code (see Figure 2-47), right-click it, and select Refactor→Extract Method.

Figure 247 Supply a new name for your method see Figure 248 You can also - фото 51

Figure 2-47

Supply a new name for your method (see Figure 2-48). You can also preview the default method signature that the refactoring engine has created for you. Click OK.

Figure 248 The block of statements is now encapsulated within a function and - фото 52

Figure 2-48

The block of statements is now encapsulated within a function and the original block of code is replaced by a call to that function:

private void Form1_Load(object sender, EventArgs e) {

Summation();

}

private static void Summation() {

int num = 10, sum = 0;

for (int i = 1; i <= num; i++) {

sum += i;

}

}

However, you still need to do some tweaking because the variable sumshould be returned from the function. The code you highlight will affect how the refactoring engine works. For example, if you include the variables declaration in the highlighting, a void function is created.

While the method extraction feature is useful, you must pay close attention to the new method signature and the return type. Often, some minor changes are needed to get what you want. Here's another example:

Single radius = 3.5f;

Single height = 5;

double volume = Math.PI * Math.Pow(radius, 2) * height;

If you exclude the variables declaration in the refactoring (instead of selecting all the three lines; see Figure 2-49) and name the new method VolumeofCylinder, a method with two parameters is created:

private void Form1_Load(object sender, EventArgs e) {

Single radius = 3.5f;

Single height = 5;

double volume = VolumeofCylinder(radius, height);

}

private static double VolumeofCylinder(Single radius, Single height) {

return Math.PI * Math.Pow(radius, 2) * height;

}

Figure 249 Here are some observations Variables that are defined outside of - фото 53

Figure 2-49

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

Интервал:

Закладка:

Сделать

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

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


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

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

x