公约的问题:当你用一个getter / setter函数,而不是使用属性 [英] Convention question: When do you use a Getter/Setter function rather than using a Property

查看:130
本文介绍了公约的问题:当你用一个getter / setter函数,而不是使用属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我留意到属性在C#试图操纵在类中的字段时,应使用。但是,当有复杂的计算和数据库参与,我们应该用一个getter / setter方法​​。

It strikes me that Properties in C# should be use when trying to manipulate a field in the class. But when there's complex calculations or database involved, we should use a getter/setter.

这是正确的?

当你使用S /消气了属性?

When do you use s/getter over properties?

推荐答案

在.NET设计指导原则提供了一些这个问题的答案在< A HREF =htt​​p://msdn.microsoft.com/en-us/library/bzwdh01d(VS.71).aspx#cpconpropertyusageguidelinesanchor1>属性与方法部分。

The .NET design guidelines provide some answers to this question in the Properties vs. Methods section.

基本上,属性具有相同的语义场。你不应该让物业抛出异常,属性应该不会有副作用,为了不应该的问题,和性能应相对快速返回。如果有这些事情都可能发生,最好的使用方法。该指南还建议使用返回数组的方法。

Basically, properties have the same semantics as a field. You shouldn't let a property throw exceptions, properties shouldn't have side effects, order shouldn't matter, and properties should return relatively quickly. If any of those things could happen, it's better to use a method. The guidelines also recommend using methods for returning arrays.

在决定是否使用属性或方法,它帮助,如果我觉得它像一个字段。我认为,对于该酒店的行为,并问自己,如果这是在类中的字段,我会感到惊讶,如果它的表现方式是这样?举个例子,在 TcpClient.GetStream方法。它可以抛出的基础上,如果连接是由几个例外,并尝试获取流之前很重要的TcpClient的配置。正因为如此,它是一个Get方法,而不是一个属性。

When deciding whether to use a property or method, it helps if I think of it like a field. I think about the behavior of the property and ask myself, "If this were a field on the class, would I be surprised if it behaved the way it does?" Consider, for example, the TcpClient.GetStream method. It can throw several exceptions based on if the connection is made, and it's important that the TcpClient is configured before you try to get the stream. Because of this, it is a Get method rather than a property.

如果您需要在设计指导好好看看,你会发现它通常的的喜好;有很好的理由使用方法而不是在某些情况下属性。

If you take a good look at the design guidelines, you'll see that it's usually not a matter of preference; there's good reasons to use methods instead of properties in certain cases.

这篇关于公约的问题:当你用一个getter / setter函数,而不是使用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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