如何:用封装字段重构代码

更新:2007 年 11 月

下面的过程描述如何从现有字段创建属性,然后通过引用新属性来更新代码。使用此过程可以执行 封装字段 重构操作。

从字段创建属性

  1. 按示例部分中所述创建控制台应用程序。

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

  2. 代码和文本编辑器 中,将光标放在声明中要封装的字段的名称上。在下面的示例中,将光标放在单词 width 上:

       public int width, height;
    
  3. 在“重构”菜单上单击“封装字段”。

    随即显示 “封装字段”对话框

    也可以通过键入键盘快捷键 Ctrl+R、Ctrl+E 来显示“封装字段”对话框。

    还可以右击光标,指向“重构”,然后单击“封装字段”以显示“封装字段”对话框。

  4. 指定设置。

  5. 按 Enter,或单击“确定”按钮。

  6. 如果选择了“预览引用更改”选项,则将打开“预览引用更改”窗口。单击“应用”按钮。

    源文件中将显示下面的 get 和 set 访问器代码:

            public int Width
            {
                get { return width; }
                set { width = value; }
            }
    

    Main 方法中的代码也将更新为新的 Width 属性名。

    Square mySquare = new Square();
    mySquare.Width = 110;
    mySquare.height = 150;
    // Output values for width and height.
    Console.WriteLine("width = {0}", mySquare.Width);
    

示例

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

class Square
{
    // Select the word 'width' then use Encapsulate Field.
    public int width, height;
}
class MainClass
{
    public static void Main()
    {
        Square mySquare = new Square();
        mySquare.width = 110;
        mySquare.height = 150;
        // Output values for width and height.
        Console.WriteLine("width = {0}", mySquare.width);
        Console.WriteLine("height = {0}", mySquare.height);
    }
}

请参见

概念

重构

参考

封装字段