GET和SET [英] GETs and SETs
问题描述
据我所知,最佳做法是隐藏方法背后的字段,但是第一百次使用
,我写了以下内容:
get {return x; }
set {x = value; }
如果那就是得到和设置的全部,那么制作x
a公共成员是不是更好? br />
5月7日晚上11:58,Dom< dolivas ... @ gmail.comwrote:
< blockquote class =post_quotes>
我明白最好的做法是隐藏方法背后的字段,但是第一百分钟是
,我写了以下内容:
得到{return x; }
set {x = value; }
如果这就是得到和设置的全部,那么公共会员只需要制作x
是不是更好?
这一切都取决于编写代码的人。如果它是你自己的个人物品并且变量公开变得容易,那就去吧。
如果你设计一个可以被更广泛的社区使用的组件
然后使用属性和方法。
你想要有人设置你公开的变量
现在你呢?它是完美的控制机制。
Vince
你想要有人设置一个你自己的变量公开
现在好吗?它是完美的控制机制。
Vince
这就是我不明白的。 get和set都是公共的
,所以你允许有人设置一个变量。无论你是
使用的是套装还是公共变量,你最终都会写这个。
MyObject.X = 10
5月8日上午12:24,Dom< dolivas ... @ gmail.comwrote:
你想要有人设置你公开的变量
现在你呢?它是完美的控制机制。
Vince
这就是我不明白的地方。 get和set都是公共的
,所以你允许有人设置一个变量。无论你是
是使用集合还是公共变量,你仍然最终写这个。
MyObject.X = 10
不是这样,如果你排除SET部分,那么它就变成了一个只读的
属性。公共变量可以操作。
别忘了你也可以在你的get和
设置块中删除一大堆代码你可以在
返回值之前设置一个内部变量。
Vince
I understand that best practice is to hide fields behind methods, but
for the hundredth time, I''ve written the following:
get { return x; }
set { x = value; }
If that''s all that get and set does, isn''t it better to just make "x"
a public member?
On May 7, 11:58 pm, Dom <dolivas...@gmail.comwrote:I understand that best practice is to hide fields behind methods, but
for the hundredth time, I''ve written the following:
get { return x; }
set { x = value; }
If that''s all that get and set does, isn''t it better to just make "x"
a public member?
It all depends on who the code is written for. If its your own
personal thing and making a variable public is easier then go for it.
If your designing a component thats to be used by the wider community
then use properties and methods.
You wouldent want someone setting a variable that you''ve made public
now would you? Its the perfect control mechanism.
Vince
You wouldent want someone setting a variable that you''ve made publicnow would you? Its the perfect control mechanism.
VinceThat''s what I don''t understand. The get and set are both public
anyway, so you are allowing someone to set a variable. Whether you
are using a set, or a public variable, you still end up writing this.
MyObject.X = 10
On May 8, 12:24 am, Dom <dolivas...@gmail.comwrote:You wouldent want someone setting a variable that you''ve made public
now would you? Its the perfect control mechanism.
Vince
That''s what I don''t understand. The get and set are both public
anyway, so you are allowing someone to set a variable. Whether you
are using a set, or a public variable, you still end up writing this.
MyObject.X = 10
Not so, if you exclude the SET part then it becomes a readonly
property. A public variable is open to manipulation.
Don''t forget you can also drop a whole bunch of code in your get and
set blocks which allow you to maybe set an internal variable before
returning the value also.
Vince
这篇关于GET和SET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!