为什么我需要使用 get 和 set?

发布于 2024-12-13 00:30:54 字数 590 浏览 1 评论 0原文

我有一个代码段:

public class MyClass
{
    private string _myProperty;

    public string MyProperty
    {
        get
        {
            return _myProperty;
        }

        set
        {
            _myProperty = value;
        }
    }
}

这里有什么意义?我可以将 _myProperty 字符串声明为公共字符串,并且我的任何类对象都可以直接访问它们并获取或设置值。

相反,我们将 _myProperty 设为私有,并使用类对象使用 get 和 set 来访问它们。

在任何一种情况下,类对象都能够访问它们,并且结果始终相同。

那么为什么要使用这种方法呢?这只是因为我可以在设置器中实现很少的约束吗?

除此之外,将成员变量公开还会带来什么危害?在此示例中,我可以将 _myProperty 公开为公共,而不是仅通过将其设置为私有来将其限制为此类,如 OOP 所建议的那样。

I have a code segment:

public class MyClass
{
    private string _myProperty;

    public string MyProperty
    {
        get
        {
            return _myProperty;
        }

        set
        {
            _myProperty = value;
        }
    }
}

What is the point here? I could have declared the _myProperty string as public and any of my class objects will be able to directly access them and get or set the value.

Instead, we are making _myProperty private and the using get and set to access them, using the class object.

In either case, the class object is able to access them and the result is always same.

So why use this approach? Is that only because I can implement few constraints in setter?

Apart from that what harm will making member variables public cause? In this example I could expose _myProperty as public instead of restricting it to this class only by making it private, as OOP would suggest.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

心碎无痕… 2024-12-20 00:30:54

不,结果并不总是相同的。

  • 尝试绑定到公共字段(或执行任何其他使用反射并需要属性的操作)
  • 尝试通过引用传递属性(您不能)
  • 尝试稍后决定您想要记录等,并在更改时发现这一点如果将其更改为属性,您将失去源代码和二进制兼容性。

阅读我不久前写的关于此问题的文章...

请注意,从 C# 2 开始不过,您的代码可以很多短:

public class MyClass
{
    public string MyProperty { get; set; }
}

No, the result isn't always the same.

  • Try binding to a public field (or doing anything else which uses reflection and expects properties)
  • Try passing a property by reference (you can't)
  • Try later deciding you want logging etc and finding that when you change it to a property, you lose both source and binary compatibility.

Read the article I wrote on this a while ago...

Note that as of C# 2 your code can be a lot shorter though:

public class MyClass
{
    public string MyProperty { get; set; }
}
无可置疑 2024-12-20 00:30:54

字段_myProperty是一个实现细节——它告诉编译器您需要一些存储空间来存储字符串引用并为其指定名称。 get/set 方法是对象属性的一部分,它抽象了如何实现MyProperty 属性。因此,如果您想更改字符串的存储/检索方式,第 3 方依赖项无需重新编译。

您还可以使用自动属性来为您执行此操作:

public string MyProperty {get; set;}

The field _myProperty is an implementation detail—it tells the compiler you want some storage for a string reference and to give it that name. The get/set methods are part of the property of the object, which abstracts how the MyProperty property is implemented. So, say, if you want to change how the string is stored/retrieved, 3rd-party dependants don't have to re-compile.

You can also use automatic properties to do this for you:

public string MyProperty {get; set;}
往事风中埋 2024-12-20 00:30:54

如果您只是将变量声明为 Public ,那么它们实际上并不是属性。许多使用反射的功能将无法工作,特别是数据绑定、序列化等。

有时我会因为懒惰而这样做,特别是在 VB.Net pre v4 中工作时,因为没有自动属性,并且总是后悔并回去正确写入属性。

如果您的类要由除您之外的开发人员编写的代码使用,那么使用属性尤其重要,因为他们很可能会因不编码完整属性而受到限制而遇到问题。

If you just declare variables as Public , these are not actually Properies. Many of the functionalities that use reflection will not work, in particular DataBinding, Serialization and so on.

Occasionally I get lazy and do this, particularly when working in VB.Net pre v4 as there are no auto properties, and always regret it and go back to write the properties in properly.

It is especially important to use properties if your class is to be consumed by code written by developers other than yourself, as they may well have problems with the limitations imposed by not coding full properties.

戏蝶舞 2024-12-20 00:30:54

正如您所说,属性的主要原因是验证。每个类都有责任保证其成员的安全,并且 _myProperty 是 MyClass 的成员。 .Net 履行这一责任的方式是财产。在 Java 中,您必须定义两个方法:SetMyPropety 和 GetMyProperty。

As you said the main reason for properties is validation. Every class has this responsibility to keep their memebers safe and _myProperty is a member of MyClass. The .Net's way for implementing this responsibility is propety. in Java you have to define two methods: SetMyPropety and GetMyProperty.

入画浅相思 2024-12-20 00:30:54

需要注意的是,虽然类将字段包装在属性中通常很有帮助,但对于结构来说这样做通常会适得其反。对结构使用的许多建议限制源于这样的假设:所有结构字段都将包装在属性中。如果结构的语义规定:

  1. 它的状态完全由固定数量的参数定义,所有这些参数都公开供读取。
  2. 这些参数可以自由地分配对其各自类型合法的值的任意组合。
  3. 结构体的默认实例被指定为将所有参数初始化为其各自类型的默认值。

那么公开字段将公开数据类型的“内部工作原理”,但这种公开不会排除未来对数据类型进行任何有意义的更改,而规范尚未排除这些更改。存储在可修改位置的所有结构体的所有字段总是暴露以进行突变,即使唯一的突变方式是将所有公共和私有字段从一个实例批量复制到另一个实例。如果结构体的语义要求代码能够创建一个实例,其定义参数具有任意值组合,而不受限制,则直接公开结构体的字段将不允许单线程代码执行任何它无法执行的操作慢慢地没有这样的访问。暴露字段将允许代码执行其他方式无法执行的唯一操作是:

  1. 执行速度更快
  2. 更清楚地表达其意图
  3. 在多线程场景中定义了语义,否则语义将是模糊的

I don't really see much benefit to requiring consumers of a type to run slower, be written awkwardly, and have murky multi-threading semantics.

请注意,如果有一个策略是禁止结构体的属性发生变化,而不是封装所有结构体字段,那么

myListOfPoint[4].X = 5;

即使该语言允许以只读方式调用属性设置器,如下语句也会被拒绝 :结构(假设其目的是为了

myArraySegment[3] = 9;

访问 myArraySegment 保存引用的数组)。

It's important to note that while it is often helpful for classes to wrap fields in properties, it is often counterproductive for structures to do so. Many of the recommended limitations on the use of structures stem from a presumption that all struct fields will be wrapped in properties. If the semantics of a struct provide that:

  1. Its state is completely defined by a fixed number of parameters, all of which are publicly exposed for reading.
  2. Those parameters may be freely assigned any combination of values that are legal for their respective types.
  3. The default instance of the struct is specified as having all parameters initialized to the default values of their respective types.

then exposing fields would expose the "inner workings" of the data type, but such exposure would not preclude any meaningful future changes to the data type which would not already be excluded by the spec. All fields of all structs that are stored in modifiable locations are always exposed for mutation, even if the only means of mutation is a bulk copy of all public and private fields from one instance to another. If the semantics of a struct require that code be able to create an instance whose defining parameters have any combination of values, without restriction, exposing a struct's fields directly won't allow single-threaded code to do anything which it couldn't do more slowly without such access. The only things exposing the fields will allow code to do which it wouldn't be able to do otherwise are:

  1. execute faster
  2. express its intention more clearly
  3. have defined semantics in multi-threading scenarios where the semantics would otherwise be murky

I don't really see much benefit to requiring consumers of a type to run slower, be written awkwardly, and have murky multi-threading semantics.

Note that if there were a policy against having structs with properties that mutate 'this', rather than a policy of encapsulating all struct fields, then a statement like:

myListOfPoint[4].X = 5;

would be rejected even if the language allowed property setters to be called on read-only structs (with a presumption that the purpose would be for things like

myArraySegment[3] = 9;

which would be understood as accessing the array to which myArraySegment holds a reference).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文