属性与方法 [英] Properties vs Methods

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

问题描述

快速问题:什么时候决定使用属性(在 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;
}

在示例中,Label 是 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.

我会接受最一般和最全面的答案,但这也涉及我给出的例子.

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:

一般来说,方法代表动作,属性代表数据.属性旨在像字段一样使用,这意味着属性不应在计算上复杂或产生副作用.如果不违反以下准则,请考虑使用属性而不是方法,因为经验不足的开发人员会发现属性更易于使用.

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.

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

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