属性(无需额外处理)与公共字段 [英] Property(with no extra processing) vs public field
问题描述
每当有关于属性可信度的问题时,我看到大部分讨论都是围绕函数/方法与属性进行的.但我也想知道令人信服的理由是直接使用具有关联私有字段与公共字段的属性本身,以防最常见的获取/设置行为而没有其他处理,我的意思是这样
Whenever there is question about credibility of Properties, I see that most of the discussion happens around functions/methods vs properties. But I would also like to know the compelling reason to use property with associated private field vs public field directly itself, incase of most common get/set behaviors with no other processing, I mean this way
public string CustomerName;
对比
private string customerName;
public string CustomerName
{
get{return customerName;}
set(string value){this.customerName=value;}
}
推荐答案
如果您以后需要添加其他行为,您将获得源代码/二进制兼容性,您可以添加断点,这只是哲学上更清晰(关心行为,不是存储机制).
You get source/binary compatibility if you later need to add other behavior, you get to add break points, and it's just philosophically cleaner (care about the behavior, not the storage mechanism).
请注意,您不需要 C# 3 中的整个后一个块:
Note that you don't need the whole of the latter block in C# 3:
public string CustomerName { get; set; }
有关详细信息,请参阅我关于为什么属性很重要"的文章.
See my article on "Why Properties Matter" for more information.
这篇关于属性(无需额外处理)与公共字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!