c# 3.0 中的新自动属性,有什么好处? [英] New automatic properties in c# 3.0, what's the benefit?

查看:47
本文介绍了c# 3.0 中的新自动属性,有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么好处:

public string User {get; set;}

结束

public string User;

既然在第一种情况下您无法访问私有成员,那么仅将您的属性设为公开有什么不同?

Since you can't access the private member in the first case, how is it any different that just making your property public?

推荐答案

第二个示例是将 field 设为公开,而不是属性(您的问题).这提供了一种制作简单属性的简单方法.属性应该是你的默认值,而不是公共字段;原因不胜枚举,但从以下几点开始:

The second example is making the field public, not a property (your question). This provides a simple way of making simple properties. Properties should be your default, not public fields; the list of reasons is endless, but starts with:

  • 封装
  • 能够添加通知
  • 封装
  • 进行验证的能力
  • 封装
  • 数据绑定
  • 封装
  • 安全检查

哦 - 我有没有提到封装?

oh - and did I mention encapsulation?

事后将字段更改为属性是一项重大更改 - 特别是如果您使用大量引用"代码或可变结构(yeuch).

Changing from a field to a property after-the-fact is a breaking change - especially if you use a lot of "ref" code or mutable structs (yeuch).

这篇关于c# 3.0 中的新自动属性,有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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