C# 中的方法与属性 - 有什么区别 [英] Method vs Property in C# - what's the difference

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

问题描述

可能的重复:
属性与方法

在方法中,您也可以输入一些代码和属性.例如,我有一个属性名称.当类名更改时,我想从数据库中获取一些数据并更改对象的状态.我可以添加此代码来设置我的部分财产.其他解决方案是将设置部分更改为私有并添加名为 SetName 的方法,并在此方法中添加我的代码.

In method you can type some code and in properties too. For example I have a property Name. When class name changes I would like to get some data from database and change state of my object. I can add this code to set part of my property. Other solution is to change set part to private and add method called SetName and in this method add my code.

那么有什么区别呢?什么时候把一些代码放到 getter/setter 中是不好的,什么时候创建自己的方法来改变我的属性和我的类的其他部分?

So what is the difference? When is the point when it's not good to put some code to getter / setter and when to create own method that is used to change my property and other parts of my class?

推荐答案

这里有一套很好的指南,用于说明何时使用 Bill Wagner(固定链接)

Here is a good set of guidelines for when to use properties vs methods from Bill Wagner (fixed link)

  • 当所有这些都为真时使用属性:getter 应该很简单,因此不太可能抛出异常.请注意,这意味着没有网络(或数据库)访问.两者都可能失败,因此会引发异常.
  • 它们不应该相互依赖.请注意,这将包括设置一个属性并使其影响另一个属性.(例如,设置 FirstName 属性会影响由名字 + 姓氏属性组成的只读 FullName 属性暗示了这种依赖关系)
  • 它们应该以任何顺序设置
  • getter 没有可观察到的副作用 请注意,本指南不排除属性中某些形式的惰性求值.
  • 该方法必须始终立即返回.(请注意,这排除了进行数据库访问调用、Web 服务调用或其他类似操作的属性).
  • 如果成员返回数组,则使用方法.
  • 重复调用 getter(没有中间代码)应该返回相同的值.
  • 对 setter 的重复调用(具有相同的值)应该与单次调用没有区别.

  • Use a Property when all these are true: The getters should be simple and thus unlikely to throw exceptions. Note that this implies no network (or database) access. Either might fail, and therefore would throw an exception.
  • They should not have dependencies on each other. Note that this would include setting one property and having it affect another. (For example, setting the FirstName property would affect a read-only FullName property that composed the first name + last name properties implies such a dependency )
  • They should be settable in any order
  • The getter does not have an observable side effect Note this guideline doesn't preclude some forms of lazy evaluation in a property.
  • The method must always return immediately. (Note that this precludes a property that makes a database access call, web service call, or other similar operation).
  • Use a method if the member returns an array.
  • Repeated calls to the getter (without intervening code) should return the same value.
  • Repeated calls to the setter (with the same value) should yield no difference from a single call.

get 不应返回对内部数据结构的引用(参见第 23 条).一个方法可以返回一个深拷贝,并且可以避免这个问题.

The get should not return a reference to internal data structures (See item 23). A method could return a deep copy, and could avoid this issue.

这篇关于C# 中的方法与属性 - 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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