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

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

问题描述


可能重复:

Properties vs Methods

在方法中,您可以在属性中键入一些代码。例如我有一个属性名称。当类名更改时,我想从数据库中获取一些数据,并改变我的对象的状态。我可以添加这段代码来设置我的属性的一部分。其他解决方案是将set部分更改为private并添加名为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没有可观察到的副作用注意,此指南不排除某个属性中的某些形式的延迟评估。

  • 该方法必须始终返回立即。 (请注意,这会排除执行数据库访问调用,网络服务调用或其他类似操作的属性)。

  • 如果成员返回数组,请使用方法。

  • 重复调用getter(没有插入代码)应该返回相同的值。

对设置者重复调用(具有相同的值)不会产生任何差异。

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.

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

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