公共字段与自动属性 [英] Public Fields versus Automatic Properties
问题描述
我们经常被告知我们应该通过getter和setter方法(在C#属性)类领域,而不是暴露领域向外界保护封装。
但也有很多时候一个字段是只是为了保持一个值,并且不需要任何计算以获取或设置。对于这些我们都做到这个数字:
公共类图书
{
私人字符串_title; 公共字符串标题
{
{返回_title; }
集合{_title =价值; }
}
}
好吧,我有一个秘密,我不忍写所有的(实际上,它是没有写出来,这是不必看它),所以我去流氓和使用的公共领域。
然后来了C#3.0和我看到他们增加了自动属性:
公共类图书
{
公共字符串名称{搞定;组;}
}
这是整洁的,我很感激,但说真的,有什么比只是让公共领域?
如此不同 公共类图书
{
公共字符串称号;
}
在一个相关问题我以前有一段时间,有一个帖子中的链接杰夫的博客,解释一些差异。
- 反射原理不同的变量与属性,因此,如果你靠反射,它更容易使用的所有属性。
- 您不能对数据绑定变量。
-
变量更改为一个属性是一个重大更改。例如:
TryGetTitle(出book.Title); //需要一个变量
We're often told we should protect encapsulation by making getter and setter methods (properties in C#) for class fields, instead of exposing the fields to the outside world.
But there are many times when a field is just there to hold a value and doesn't require any computation to get or set. For these we would all do this number:
public class Book
{
private string _title;
public string Title
{
get{ return _title; }
set{ _title = value; }
}
}
Well, I have a confession, I couldn't bear writing all that (really, it wasn't having to write it, it was having to look at it), so I went rogue and used public fields.
Then along comes C# 3.0 and I see they added automatic properties:
public class Book
{
public string Title {get; set;}
}
which is tidier, and I'm thankful for it, but really, what's so different than just making a public field?
public class Book
{
public string Title;
}
In a related question I had some time ago, there was a link to a posting on Jeff's blog, explaining some differences.
Properties vs. Public Variables
- Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
- You can't databind against a variable.
Changing a variable to a property is a breaking change. For example:
TryGetTitle(out book.Title); // requires a variable
这篇关于公共字段与自动属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!