C# 中的方法与属性 - 有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1294152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:47:48  来源:igfitidea点击:

Method vs Property in C# - what's the difference

c#classooppropertiesmethods

提问by Tomasz Smykowski

Possible Duplicate:
Properties vs Methods

可能的重复:
属性与方法

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.

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

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?

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

采纳答案by Chris Ballance

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

这是Bill Wagner 提供的关于何时使用属性与方法的一组很好的指南(固定链接)

  • 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.

  • 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.

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

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

回答by plinth

Given a property like this

给定这样的属性

private string _name;
public string Name { get { return _name; } set { _name = value; } }

it is possible to write the following two methods:

可以编写以下两种方法:

public string get_Name() { return _name; }
public void set_Name(string value) { _name = value; }

which act identically. And in fact, this is exactly what the compiler does for you when you create a property.

其行为相同。事实上,这正是您创建属性时编译器为您所做的。

Generally speaking, I steer away from properties when the code within them starts to feel "expensive", if that makes any sense. I want properties to feel like fields (with controlled side effects that happen at specific times), so they should be lightweight.

一般来说,当属性中的代码开始感觉“昂贵”时,我会避开属性,如果这有意义的话。我希望属性感觉像字段(具有在特定时间发生的受控副作用),因此它们应该是轻量级的。

回答by Frederik Gheysels

A property is nothing but some syntactic sugar. In some cases, it is better to define a property instead of a method because it is clearer / more readable.

属性只不过是一些语法糖。在某些情况下,最好定义一个属性而不是一个方法,因为它更清晰/更具可读性。

Design guidelines state that, when the functionality you're implementing is expensive, a method should be preferred over a property.

设计指南指出,当您实现的功能很昂贵时,应该首选方法而不是属性。

in fact, a property is implemented as one or two methods; depending whether your property has a setter or not. The property is translated into a get_xxx and a set_xxx method.

事实上,一个属性被实现为一两个方法;取决于您的财产是否有二传手。该属性被转换为 get_xxx 和 set_xxx 方法。

回答by Scott Vercuski

Whenever I've come across the need to put code in a getter/setter I put the code in a private method and call that method from within the getter/setter. That way the code is available in a method call should I need it elsewhere. Not sure if this is the answer you were seeking but it is just a methodology I use.

每当我遇到需要将代码放入 getter/setter 时,我都会将代码放入私有方法中,并从 getter/setter 中调用该方法。这样,如果我在其他地方需要它,代码就可以在方法调用中使用。不确定这是否是您正在寻找的答案,但这只是我使用的一种方法。

回答by Rashack

Essentially a property is a couple of methods - getProperty and setProperty. It is only the convention / simplification of the thing.

本质上,一个属性是几个方法——getProperty 和 setProperty。这只是事物的约定/简化。

It is assumed that property getter has no side effects (well - they might have certain side effect, like lazy loading).

假设属性 getter 没有副作用(好吧 - 它们可能有某些副作用,比如延迟加载)。

回答by ChrisW

This probably isn't the most important difference, but one of the differences is that the debugger can be configured to step over properties (assuming their code is trivial).

这可能不是最重要的区别,但区别之一是调试器可以配置为跳过属性(假设它们的代码很简单)。

回答by ChrisW

There is basically no difference (except for the reserved identifier "value" in a setter).

基本上没有区别(除了 setter 中的保留标识符“值”)。

Getters and setters get internally translated into standard methods such that the runtime has no idea whether some getter or setter is associated with a certain property. The term syntactic sugar is often used for convenience constructs like these.

Getter 和 setter 在内部被转换为标准方法,因此运行时不知道某些 getter 或 setter 是否与某个属性相关联。术语语法糖通常用于像这样的方便构造。

However, there is an important software engineering benefit: your code tends to be easier to understand if you restrict yourself to use getters and setters with get and set semantics. I.e. do only the steps necessary to provide the respective property.

但是,有一个重要的软件工程好处:如果您限制自己使用具有 get 和 set 语义的 getter 和 setter,您的代码往往更容易理解。即只执行提供相应属性所需的步骤。

A common use case for doing a bit of extra work is for instance the setting or getting of a property which is not directly backed by a member field. For example, you've got a class that contains say a value that represents a distance. Your class could provide two Properties: Kilometers and Miles with respective setters and getters. Then you would do simple conversions in one pair and save yourself to store the value twice.

做一些额外工作的常见用例是例如设置或获取不直接由成员字段支持的属性。例如,您有一个包含表示距离的值的类。您的类可以提供两个属性:Kilometers 和 Miles 以及各自的 setter 和 getter。然后你会在一对中进行简单的转换,并保存自己两次存储该值。

As a general rule of thumb, you should not put any code in a getter that has side effects. Also, the only side effect that code in a setter should have is the change of state in the object the setter refers to.

作为一般经验法则,您不应将任何代码放入具有副作用的 getter 中。此外,setter 中的代码应该具有的唯一副作用是 setter 引用的对象中的状态更改。

回答by Jarvis Bot

Coming to think of it, Properties are more than just syntactic sugar. They are the public face of your member data to you member code.

仔细想想,Properties 不仅仅是语法糖。它们是您的会员数据对您的会员代码的公开面孔。

Thus, giving you a clean layer for retrieval or input of a single aspect of you member data from you code.

因此,为您提供了一个干净的层,用于从代码中检索或输入成员数据的单个方面。

A DTO for example is nothing but a bunch of well written properties, cleaving data and behavior efficiently. Without a DTO would you imagine tightly coupling your DataGrid or Dropdown to complex business logic method?

例如,DTO 只不过是一堆写得很好的属性,有效地分割数据和行为。如果没有 DTO,您会想象将 DataGrid 或 Dropdown 与复杂的业务逻辑方法紧密耦合吗?

Put it simply, Methods are actually doing the work...Properties either instigate action or get the status.

简单地说,方法实际上是在做工作……属性要么煽动行动,要么获得状态。

Though, you can use method code inside your properties ...it is not what they are meant for. Even, if you have to you are better of making a clean call to another method inside the property instead of actually writing you code in it. HTH!

但是,您可以在属性中使用方法代码……这不是它们的用途。甚至,如果必须的话,最好对属性内的另一个方法进行干净的调用,而不是实际在其中编写代码。哼!