.NET - 当我应该使用属性与变量+存取函数? [英] .NET - When should I use a property vs. variable + accessor function?

查看:191
本文介绍了.NET - 当我应该使用属性与变量+存取函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有过的情况下我应该做到以下几点。NET中,而不是使用属性与读/写功能?

Is there ever a situation where I should do the following in .NET instead of using a property with read/write capability?

private S as string

public function GetS() as string
     return S
end function

public sub SetS(byval NewS as string)
    S = NewS
end function

做的属性只是为了做同样的事情提供了更有效的方法?

Do properties simply provide a more efficient way for doing the same thing?

将性能比上面的访问功能的任何放缓高性能的应用程序?

Will properties be any slower than the above accessor functions in a high performance application?

推荐答案

属性,在内部,都不过是对方法。他们基本上得出一个get和set访问方法。

Properties, internally, are nothing but a pair of methods. They basically evaluate to a get and set accessor method.

您应该使用属性,除非该属性会造成一些意想不到的,可能长时间运行的副作用,或者有使用方法,其他一些很好的理由。

You should use properties, unless the property is going to cause some unexpected, potentially long running side effect, or there is some other good reason to use a method.

有关详细信息,我建议您阅读MSDN上的物业使用指南。特别是,使用的方法时:

For details, I suggest reading the Property Usage Guidelines on MSDN. In particular, use a method when:

  • 的操作的转换,如Object.ToString。
  • 的操作是要传达给他们应考虑缓存结果的用户够贵。
  • 使用get访问将有一个观察到的副作用获得一个属性值。
  • 在连续调用两次成员会产生不同的结果。
  • 执行的顺序是非常重要的。注意,类型的属性应该能够设置和检索任何顺序。
  • 的成员是静态的,但是返回可以更改的值。
  • 在该成员返回一个数组。

否则,我会使用一个属性。 布拉德·艾布拉姆的博客上其他一些细节的,包括良好的原因,某些API函数使用方法(主要是因为他们可能会导致跨计算机通信,这将陷入副作用的范畴)。

Otherwise, I'd use a property. Brad Abram's blogged some other details, including good reasons why certain API functions use methods (mostly because they could cause cross-computer communication, which would fall into the "side effect" category).

这篇关于.NET - 当我应该使用属性与变量+存取函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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