在什么情况下应使用公共字段代替属性? [英] In what cases should public fields be used instead of properties?

查看:155
本文介绍了在什么情况下应使用公共字段代替属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
公共数据成员与Getter,Setters

Possible Duplicate:
Public Data members vs Getters, Setters

在什么情况下应使用公共字段,而不是属性或getter和setter方法(不支持属性)?建议在哪里使用它们?为什么?如果不是,为什么仍然允许将它们作为语言功能使用?毕竟,它们违反了允许和鼓励使用getter和setter的封装的面向对象原则.

In what cases should public fields be used, instead of properties or getter and setter methods (where there is no support for properties)? Where exactly is their use recommended, and why, or, if it is not, why are they still allowed as a language feature? After all, they break the Object-Oriented principle of encapsulation where getters and setters are allowed and encouraged.

推荐答案

很难说,但是在我看来,公共字段仅在使用结构体时有效.

That's hard to tell, but in my opinion public fields are only valid when using structs.

struct Simple
{
    public int Position;
    public bool Exists;
    public double LastValue;
};

但是不同的人有不同的想法:

But different people have different thoughts about:

http://kristofverbiest.blogspot .com/2007/02/public-fields-and-properties-are-not.html

http ://blogs.msdn.com/b/ericgu/archive/2007/02/01/properties-vs-public-fields-redux.aspx

http://www.markhneedham.com/blog/2009/02/04/c-public-fields-vs-automatic-properties/

这篇关于在什么情况下应使用公共字段代替属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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