在C#中的属性或变量 [英] Properties Or Variables in C#

查看:117
本文介绍了在C#中的属性或变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/3069901/properties-vs-fields-need-help-grasping-the-uses-of-properties-over-fields">Properties主场迎战领域:需要帮助抓过场性质的用途

我已经看到在类的属性和变量。

I have seen properties and variables in class.

可否请你让我知道这场景中,我们使用的财产,哪些场景中,我们使用的变量。

Could you please let me know which scenario we use property and which scenario we use variable.

推荐答案

通常情况下,一个属性的备份的一个变量反正。即使你有一个这样的自动实现的属性:

Usually, a property is backed by a variable anyway. Even if you have an automatically implemented property like this:

public string Name { get; set; }

仍然在幕后的变量。不是的所有的属性由变量支持(例如 DateTime.Now ),但绝大多数都是。

there still a variable behind the scenes. Not all properties are backed by variables (e.g. DateTime.Now) but the vast majority are.

您应该无形中的总是的使用属性,从另一种类型的访问数据,而不是暴露的变量。 (换句话说,该变量本身应该是私有的。)你分离其的执行的......究竟是如何一类存储类的 API 的这样的数据应该只关注类本身。

You should virtually always use a property to access data from another type, rather than exposing the variables. (In other words, the variables themselves should be private.) That way you're separating the API of the class from its implementation... exactly how a class stores its data should only concern the class itself.

如果您的只有的不断引用类本身中的数据块,你并不真正需要的属性可言,除非你想执行验证,当你改变它,或者类似的东西。

If you only ever refer to a piece of data within the class itself, you don't really need a property at all, unless you want to perform validation when you're changing it, or something like that.

您是通过财产公开一个变量之前这是值得认真思考 - 如果你只是做这一切的时候,你失去了一定的封装;类型不应该平时的只是的是由其他code操纵数据的集合。他们应该利用他们内部的数据,揭露更高级别的操作。这有点很难形容,我并不是说性能的的本身 - 只是,他们可以,如果你不小心被滥用

It's worth thinking carefully before you expose a variable via a property - if you just do it all the time, you lose a certain amount of encapsulation; types shouldn't usually just be collections of data manipulated by other code. They should use the data within them to expose higher-level operations. It's somewhat hard to describe, and I'm not saying that properties are bad per se - just that they can be overused if you're not careful.

这篇关于在C#中的属性或变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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