logo search
CSharp_Prog_Guide

Извлечение метода

Извлечение метода — это операция оптимизации, обеспечивающая простой способ создания нового метода из фрагмента кода существующего члена.

С помощью операции Извлечение метода можно создать новый метод путем извлечения выделенного кода, находящегося внутри блока кода существующего члена. Новый, извлеченный метод содержит выделенный код, а выделенный код в существующем члене меняется на вызов нового метода. Превращение фрагмента кода в отдельный метод позволяет быстро и точно реорганизовать код с целью его много кратного использования и лучшей читаемости.

Операция Извлечение метода позволяет получить следующие преимущества:

При использовании описательных имен методы верхнего уровня можно читать как последовательности комментариев.

How to: Refactor Code with Extract Method

The following procedure describes how to create a new method from a code fragment of an existing member. Use this procedure to perform the Extract Method refactoring operation.

To use Extract Method

  1. Create a console application.

  2. In the Code Editor, select the code fragment you want to extract:

    double area = PI * radius * radius.

  3. On the Refactor menu, click Extract Method.

The Extract Method dialog box appears.

Alternatively, you can also type the keyboard shortcut CTRL+R, M to display the Extract Method dialog box.

You can also right-click the selected code, point to Refactor, and then click Extract Method to display the Extract Method dialog box.

  1. Specify a name for the new method, such as CircleArea, in the New Method Name box.

A preview of the new method signature displays under Preview Method Signature.

  1. Click OK.

Example

To set up this example, create a console application named ExtractMethod, and then replace Program with the following code.

class A

{

const double PI = 3.141592;

double CalculatePaintNeeded(double paintPerUnit, double radius)

{

// Select any of the following:

// 1. The entire next line of code.

// 2. The right-hand side of the next line of code.

// 3. Just "PI *" of the right-hand side of the next line

// of code (to see the prompt for selection expansion).

// 4. All code within the method body.

// ...Then invoke Extract Method.

double area = PI * radius * radius;

return area / paintPerUnit;

}

}