gpt4 book ai didi

c# - 自动封装字段重构, 'Use field' 和 'Use Property' 之间的区别?

转载 作者:太空宇宙 更新时间:2023-11-03 19:47:25 26 4
gpt4 key购买 nike

在 Visual Studio 2017 上,我在使用自动封装字段重构工具时有两个选择:

  1. 使用属性
  2. 仍然使用字段

Screenshot of the menu in French.

我已经在基础类(class)上测试了不同的选项:

public class Test_EncapsulateFieldRefactoring_Property
{
public int id;
public string name;
}

但是这两个选项给出了相同的结果:

public class Test_EncapsulateFieldRefactoring_Property
{
private int id;
private string name;

public int Id { get => id; set => id = value; }
public string Name { get => name; set => name = value; }
}

为什么存在这些选项?区别在哪里(在生成的代码中,“useage”*)?



免责声明:

  • 屏幕截图是关于 French VS 的。所以选项翻译是我做的,真正的选项文本可能会有所不同。
  • 我知道字段和属性之间的区别。我已经检查了很多主题,看看它是否不是一个骗局。我可能会错过一个。
  • *,找不到一个好的翻译:“in the way you use it”。但在这种情况下,不是作为字段和属性之间使用的区别,而是在菜单选项中的区别。

最佳答案

在英文中,选项称为:

  • 封装字段(并使用属性)
  • 封装字段(但仍然使用字段)

区别在于它对字段的用法 做了什么。第一个选项将更新该字段的所有用法以使用它创建的新属性。第二个选项不会更改代码中其他地方的字段的现有用法。

因此,如果您在其他地方有此代码:

var test = new Test_EncapsulateFieldRefactoring_Property();
test.name = "Hello";

您会发现第一个选项将 test.name 更新为新的 test.Name 属性,但第二个选项不会。

关于c# - 自动封装字段重构, 'Use field' 和 'Use Property' 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43756486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com