当使用get和set在C#中的属性 [英] When to use get and set properties in C#

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

问题描述

当我们要在C#中使用get和set属性?

When should we use get and set properties in C#?

推荐答案

据该的属性使用指南MSDN上的:


  • 当构件是一个逻辑数据成员使用的属性。在下面的成员声明,​​名称是一个属性,因为它是类的逻辑成员

  • Use a property when the member is a logical data member. In the following member declarations, Name is a property because it is a logical member of the class.

使用的方法时:


  • 的操作是转换,如 Object.ToString

  • 操作是要传达给他们应考虑缓存结果用户够贵的。

  • 获取使用get访问将有一个可观察到的副作用的属性值。

  • 在连续调用两次成员会产生不同的结果。

  • 执行的顺序是非常重要的。需要注意的是一个类型的属性应该是能够被设置和检索任何顺序。

  • 成员是静态的,而是返回一个可以改变的值。

  • 成员返回一个数组。返回数组的属性可以是非常误导的。通常有必要返回内部数组的副本,使得用户不能改变内部状态。此,加上一个事实,即用户可以容易地假设它是一个索引属性,导致低效的代码。在下面的代码示例中,每个调用方法属性创建数组的一个副本。其结果是,阵列的2n + 1个副本将在下面的循环中创建。

  • The operation is a conversion, such as Object.ToString.
  • The operation is expensive enough that you want to communicate to the user that they should consider caching the result.
  • Obtaining a property value using the get accessor would have an observable side effect.
  • Calling the member twice in succession produces different results.
  • The order of execution is important. Note that a type's properties should be able to be set and retrieved in any order.
  • The member is static but returns a value that can be changed.
  • The member returns an array. Properties that return arrays can be very misleading. Usually it is necessary to return a copy of the internal array so that the user cannot change internal state. This, coupled with the fact that a user can easily assume it is an indexed property, leads to inefficient code. In the following code example, each call to the Methods property creates a copy of the array. As a result, 2n+1 copies of the array will be created in the following loop.

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

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