房产VS功能(特别是.NET) [英] Property vs Function (specifically .NET)

查看:181
本文介绍了房产VS功能(特别是.NET)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过关于这个问题的一些讨论,有件事情我就是不明白。

I've read some discussions about this subject, and there's something I just don't understand.

最常见的答案似乎是这样的:用一个只读属性返回缓存数据,使用函数返回非缓存数据。不要使用只写属性可言,造成它没有任何意义。

The most common answer seems to be this: use a ReadOnly Property to return cached data, use a Function to return non-cached data. Don't use a WriteOnly Property at all, cause "it doesn't make sense".

目前对此并没有表现的原因。在IL中,存在myProperty的如 get_MyProperty set_MyProperty 的方法。唯一的原因是显然的是,以上的答案应该假设。

There is no performance reason for this. In IL, MyProperty exists as get_MyProperty and set_MyProperty methods. The only reason is apparently that the above answer should be assumed.

好了,那么为什么用只读属性在所有的烦恼呢?为什么不把这些变量公众而不是私人? 那么,为什么费心的属性呢?缓存数据 - >公变,非缓存数据 - >功能,写入数据 - >分

Ok, then why bother with ReadOnly Properties at all? Why not just make the variable Public instead of Private? Then why bother with Properties at all? Cached data -> Public variable, non-cached data -> Function, writing data -> Sub

让我们忘记所有的上面,并使用属性作为一个方便的功能? 一个项目来获取和设置数据。使用常识知道,如果一个Get不会返回缓存的数据(这可能会造成延迟)。

Let's forget all the above, and use Properties as a handy feature? One 'item' to Get and Set data. Use common sense to know if a Get will not return cached data (possibly resulting in a delay).

-Edit- 我看到人们或多或少同意属性是最好的选择。 我就是不明白,为什么我发现这么多的讨论里,人们被抨击属性。

-Edit- I see people more or less agree that Properties are the best option. I just couldn't understand why I found so many discussions where people were advocating against Properties.

推荐答案

一个很好的理由为只读属性计算的值。在这种情况下,不存在可变导出

A good reason for read only properties are values that are calculated. In this case there is no variable to export.

例如

public class Person {
  private readonly DateTime _birthday;
  public int Age { get { return (DateTime.Now - _birthday).TotalYears; } }
  ...
}

在这种情况下,是否公开_birthday作为属性或字段肯定是值得商榷的。但是,对于像年龄其它计算值,只有这样才能将它们公开为一个变量是将它们存储在该对象。在这种情况下,具有用于年龄一个额外的变量基本上是存储冗余信息。揭露它作为计算的酒店有轻微的开销,并避免了存储冗余数据。

In this case whether to expose _birthday as a property or a field is certainly debatable. But for other calculated values like Age, the only way to expose them as a variable is to store them in the object. In this case having an extra variable for Age is essentially storing redundant information. Exposing it as calculated property has minor overhead and avoids storing redundant data

这篇关于房产VS功能(特别是.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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