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

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

问题描述

我看到的C#类很多例子code的,做这样的:

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; }
}

或者,在旧的code,具有显式的私人后盾的价值,没有新的自动实现的属性是一样的:

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.

杰夫阿特伍德的几年前处理此。他回顾指出最重要的一点是,从一个字段改变为属性是断变化在code;任何消费就必须重新编译与新的类接口的工作,因此,如果你的控制范围之外的事情在消费类可能遇到的问题。

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天全站免登陆