自动实现的 getter 和 setter 与公共字段 [英] Auto-implemented getters and setters vs. public fields

查看:31
本文介绍了自动实现的 getter 和 setter 与公共字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多 C# 类的示例代码都是这样做的:

I see a lot of example code for C# classes that does this:

public class Point {
    public int x { get; set; }
    public int y { get; set; }
}

或者,在较旧的代码中,具有显式私有支持值且没有新的自动实现的属性的代码相同:

Or, in older code, the same with an explicit private backing value and without the new auto-implemented properties:

public class Point {
    private int _x;
    private int _y;

    public int x {
        get { return _x; }
        set { _x = value; }
    }

    public int y {
        get { return _y; }
        set { _y = value; }
    }
}

我的问题是为什么.执行上述操作与仅将这些成员设为公共字段(如下所示)之间在功能上有什么区别吗?

My question is why. Is there any functional difference between doing the above and just making these members public fields, like below?

public class Point {
    public int x;
    public int y;
}

明确地说,当您需要对基础数据进行一些转换时,我理解 getter 和 setter 的价值.但在您只是传递值的情况下,这似乎是不必要的冗长.

To be clear, I understand the value of getters and setters when you need to do some translation of the underlying data. But in cases where you're just passing the values through, it seems needlessly verbose.

推荐答案

我倾向于同意(这似乎是不必要的冗长),尽管这是我们团队尚未解决的问题,因此我们的编码标准仍然坚持所有类的详细属性.

I tend to agree (that it seems needlessly verbose), although this has been an issue our team hasn't yet resolved and so our coding standards still insist on verbose properties for all classes.

Jeff Atwood 几年前处理过这个问题.他回顾性指出的最重要的一点是,从字段变为属性是一个破坏性更改 在您的代码中;任何使用它的东西都必须重新编译才能使用新的类接口,因此如果您控制之外的任何东西正在使用您的类,您可能会遇到问题.

Jeff Atwood dealt with this a few years ago. The most important point he retrospectively noted is that changing from a field to a property is a breaking change in your code; anything that consumes it must be recompiled to work with the new class interface, so if anything outside of your control is consuming your class you might have problems.

这篇关于自动实现的 getter 和 setter 与公共字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆