如何:使用“提取方法”重构代码

更新:2007 年 11 月

下面的过程描述如何从现有成员的代码段来创建新的方法。使用此过程可以执行提取方法重构操作。

使用“提取方法”

  1. 创建一个控制台应用程序。

    有关更多信息,请参见 创建控制台应用程序 (Visual C#)

  2. 代码编辑器中选择要提取的代码段:

    double area = PI * radius * radius.
    
  3. 在“重构”菜单上,单击“提取方法”。

    出现“提取方法”对话框。

    也可以键入键盘快捷键 Ctrl+R、Ctrl+M 来显示“提取方法”对话框。

    还可以右击选定代码,指向“重构”,然后单击“提取方法”来显示“提取方法”对话框。

  4. 在“新方法名称”框中指定新方法的名称,如 CircleArea。

    新方法签名的预览显示在“预览方法签名”下。

  5. 单击“确定”。

示例

若要建立此示例,请创建一个名为 ExtractMethod 的控制台应用程序,然后使用以下代码替换 Program。有关更多信息,请参见 创建控制台应用程序 (Visual C#)

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

请参见

概念

重构

参考

提取方法