更新:2007 年 11 月
下面的过程描述如何从现有字段创建属性,然后通过引用新属性来更新代码。使用此过程可以执行 封装字段 重构操作。
从字段创建属性
按示例部分中所述创建控制台应用程序。
有关更多信息,请参见 创建控制台应用程序 (Visual C#)。
在 代码和文本编辑器 中,将光标放在声明中要封装的字段的名称上。在下面的示例中,将光标放在单词 width 上:
public int width, height;
在“重构”菜单上单击“封装字段”。
随即显示 “封装字段”对话框。
也可以通过键入键盘快捷键 Ctrl+R、Ctrl+E 来显示“封装字段”对话框。
还可以右击光标,指向“重构”,然后单击“封装字段”以显示“封装字段”对话框。
指定设置。
按 Enter,或单击“确定”按钮。
如果选择了“预览引用更改”选项,则将打开“预览引用更改”窗口。单击“应用”按钮。
源文件中将显示下面的 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);
}
}