属性VS方法 [英] Properties vs Methods

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

问题描述

快速的问题:当你决定使用属性(C#),当你决定要使用的方法。

Quick question: When do you decide to use properties (in C#) and when do you decide to use methods?

我们都很忙有这个辩论,并已发现一些地方是值得商榷的,我们是否应该使用一个属性或方法。一个例子是这样的:

We are busy having this debate and have found some areas where it is debatable whether we should use a property or a method. One example is this:

public void SetLabel(string text)
{
    Label.Text = text;
}

在这个例子中,标签是一个ASPX页面上的控制。有没有可以支配的决定(在这种情况下)是否使这个方法或属性的一个原则。

In the example, Label is a control on a ASPX page. Is there a principle that can govern the decision (in this case) whether to make this a method or a property.

我会接受这是最普遍和COM prehensive答案,但也触及了我所给出的例子。

I'll accept the answer that is most general and comprehensive, but that also touches on the example that I have given.

推荐答案

从的属性和方法为类库开发设计指南的部分之间进行选择:

From the Choosing Between Properties and Methods section of Design Guidelines for Developing Class Libraries:

在一般情况下,两种方法重新present行为和属性重新present数据。性质意味着像领域中使用,这意味着属性不应该是计算上复杂的或产生的副作用。当它不违反以下原则,可以考虑使用属性,而不是一个方法,因为缺乏经验的开发人员发现性能更容易使用。

In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use.

这篇关于属性VS方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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