属性与 get 的区别;放;并且没有得到;放; [英] Difference between Properties with get; set; and without get; set;

查看:23
本文介绍了属性与 get 的区别;放;并且没有得到;放;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白静态属性之间的区别:

I do not understand the difference between static properties:

public static int intId;

并获取;设置;属性:

and get;set; properties:

public int intId
{
  get
  {
    return intId;
  }
  set
  {
    intId = value;
  }
}

这两者有什么区别?它们的工作方式相同还是不同?

What is the difference between these two? They work like same or different?

推荐答案

您的第一个示例是一个字段,而不是一个属性.

Your first sample is a field, not a property.

始终将字段设为私有是一种很好的做法,而是将它们包装在属性中.

It's a good practice to always make fields private, and wrap them in properties instead.

这样你就可以在后代中的 set 或 override 属性上添加验证(如果它被标记为虚拟).您也可以在 get 和 set 中添加一些棘手的代码,这些代码将对使用您的类的人隐藏.

That way you can add validation on set or override property in descendants(if it is marked as virtual). Also you can add some tricky code in get and set that will be hidden from those who use your class.

这篇关于属性与 get 的区别;放;并且没有得到;放;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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