公共字段与自动属性 [英] Public Fields versus Automatic Properties

查看:167
本文介绍了公共字段与自动属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们经常被告知我们应该通过为类字段使用getter和setter方法(C#中的属性)来保护封装,而不是将字段暴露给外部世界。

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.

然后沿着C#3.0,我看到他们添加自动属性:

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


推荐答案

http://stackoverflow.com/questions/9304/\">相关问题我有一段时间之前,有一个链接到Jeff的博客上的发布,解释一些差异。

In a related question I had some time ago, there was a link to a posting on Jeff's blog, explaining some differences.

属性与公开变量


  • 反射在变量和属性上的工作方式不同,因此如果依赖反射,则更容易使用所有属性。

  • 不能对变量进行数据绑定。

  • 将变量更改为属性是一个突变。例如:

  • 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屋!

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