领域和财产彼此之间的优势 [英] advantages of Field and Property on each other

查看:80
本文介绍了领域和财产彼此之间的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有字段
我们有道具(代码片段).

我们应该比较还是每个人都有自己的功能.

或一般功能都

谢谢问候
James

we have fields
and we have the prop(code snippets).

shall we compare or each has own funcionality.

or general functionality is both

Thanks& Regards
James

推荐答案

它们是不同的东西:

字段是数据变量.
属性是一对方法,它们就像是一个字段一样被访问.

属性可以具有关联的字段(称为后备字段"或后备存储"),或者可以自动实现,也可以动态生成数据.

通常,将字段公开是一种不好的做法-改用Properties,因为这意味着您可以控制外界如何访问您的类数据.公开显示字段会锁定类的设计,并使其难以维护.
They are different things:

A Field is a data variable.
A Property is a pair of methods which are accessed as if they were a field.

A property may have an associated field (known as a Backing Field, or Backing Store) or it may be auto-implemented, or it may generate the data on the fly.

In general, it is considered bad practice to make fields public - use Properties instead, as this means that you can control how your class data is accessed by the outside world. Publicly exposing fields locks the design of your class, and makes it harder to maintain.


属性不过是使用get/set方法对字段的访问点.
对于外部用户而言,没有任何区别.

与字段不同,属性不是变量,可以附加验证,例如如果值是零,则set可以将其设置为null.

属性的示例是

A property is nothing but an access point to a field with a get/set method.
To the external user it makes no difference.

Unlike fields, properties are not variables and can have validations attached to them e.g. a set could set null if value is zero.

Example of a property is

string name;
public string Name
{
  get 
  {
    return name;
  }
  set 
  {
    name = value;
  }
}



Name 是属性,而name 是该属性使用的私有字段.



Name is the property and name is a private field used by the property,


在面向对象的编程中,不允许直接(或不应该)公开数据成员.为此,我们可以使用property来设置和获取值.
具体来说 [ ^ ]是您的答案.
In Object Oriented programming, you are not directly allowed (or you should not) expose data member. For that we can use property to Set and Get values.
To be very specific this[^] is your answer.


这篇关于领域和财产彼此之间的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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