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

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

Интервал:

Закладка:

Сделать

Here are some observations:

□ Variables that are defined outside of the highlighted block for refactoring are used as an input parameter in the new method.

□ If variables are declared within the block selected for refactoring, the new method will have no signature.

□ Values that are changed within the block of highlighted code will be passed into the new method by reference.

Reorder and Remove Parameters

You can use code refactoring to reorder the parameters in a function. Consider the following function from the previous example:

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

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

}

Highlight the function signature, right-click it, and select Refactor→Reorder Parameters (see Figure 2-50).

Figure 250 You can then rearrange the order of the parameter list see Figure - фото 54

Figure 2-50

You can then rearrange the order of the parameter list (see Figure 2-51).

Figure 251 Click OK You can preview the changes before they are made see - фото 55

Figure 2-51

Click OK. You can preview the changes before they are made (see Figure 2-52).

Figure 252 Once you click the Apply button your code is changed - фото 56

Figure 2-52

Once you click the Apply button, your code is changed automatically:

private void Form1_Load(object sender, EventArgs e) {

Single radius = 3.5f;

Single height = 5;

double volume = VolumeofCylinder(height, radius);

}

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

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

}

All statements that call the modified function will have their arguments order changed automatically.

You can also remove parameters from a function by highlighting the function signature, right-clicking, and selecting Refactor→Remove Parameters. Then remove the parameter(s) you want to delete (see Figure 2-53). All statements that call the modified function will have their calls changed automatically.

Figure 253 Encapsulate Field Consider the following string declaration - фото 57

Figure 2-53

Encapsulate Field

Consider the following string declaration:

namespace WindowsFormsApplication1 {

public partial class Form1 : Form {

public string caption;

private void Form1_Load(object sender, EventArgs e) {

//...

}

}

}

Instead of exposing the captionvariable as public, it is a better idea to encapsulate it as a property and use the setand getaccessors to access it. To do that, right-click on the caption variable and select Refactor→Encapsulate Field (see Figure 2-54).

Figure 254 Assign a name to your property see Figure 255 You have the - фото 58

Figure 2-54

Assign a name to your property (see Figure 2-55). You have the option to update all external references or all references (including the one within the class), and you can choose to preview your reference changes. When you're ready, click OK.

Figure 255 After youve previewed the changes see Figure 256 click Apply - фото 59

Figure 2-55

After you've previewed the changes (see Figure 2-56), click Apply to effect the change.

Figure 256 Here is the result after applying the change namespace - фото 60

Figure 2-56

Here is the result after applying the change:

namespace WindowsFormsApplication1 {

public partial class Form1 : Form {

private string caption;

public string Caption {

get { return caption; }

set { caption = value; }

}

private void Form1_Load(object sender, EventArgs e) {

//...

}

}

}

Extract Interface

You can use the refactoring engine to extract an interface from a class definition. Consider the following Contactclass:

namespace WindowsFormsApplication1 {

class Contact {

public string FirstName {

get; set;

}

public string LastName {

get; set;

}

public string Email {

get; set;

}

public DateTime DOB {

get; set;

}

}

}

Right-click the Contactclass name and select Refactor→Extract Interface (see Figure 2-57).

Figure 257 The Extract Interface dialog opens and you can select the - фото 61

Figure 2-57

The Extract Interface dialog opens, and you can select the individual public members to form the interface (see Figure 2-58).

Figure 258 The new interface is saved in a new cs file In this example the - фото 62

Figure 2-58

The new interface is saved in a new .cs file. In this example, the filename is IContact.cs:

using System;

namespace WindowsFormsApplication1 {

interface IContact {

DateTime DOB { get; set; }

string Email { get; set; }

string FirstName { get; set; }

string LastName { get; set; }

}

}

The original Contactclass definition has now been changed to implements the newly created interface:

class Contact : WindowsFormsApplication1.IContact {

public string FirstName

...

Promote Local Variable to Parameter

You can promote a local variable into a parameter. Here's an example:

private void Form1_Load(object sender, EventArgs e) {

LogError("File not found.");

}

private void LogError(string message) {

string SourceFile = "Form1.cs";

Console.WriteLine(SourceFile + ": " + message);

}

You want to promote the variable SourceFileinto a parameter so that callers of this function can pass in its value through an argument. To do so, select the variable SourceFile, right-click, and then select Refactor→Promote Local Variable to Parameter (see Figure 2-59).

Figure 259 Note that the local variable to be promoted must be initialized or - фото 63

Figure 2-59

Note that the local variable to be promoted must be initialized or an error will occur. The promoted variable is now in the parameter list and the call to it is updated accordingly:

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

Интервал:

Закладка:

Сделать

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

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


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

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

x