如果你从类中使用存取器属性,或者只是从类之外?如果你、是从、类中、属性

2023-09-04 00:15:20 作者:偶尔合群

我有一个使用一个getter访问某些阵列一类的数据。如果数组为空的话,我想数据访问该文件,填补了数组,然后返回特定的值。

I have a class 'Data' that uses a getter to access some array. If the array is null, then I want Data to access the file, fill up the array, and then return the specific value.

现在,这里是我的问题:

Now here's my question:

在创建getter和setter应该也使用相同的访问属性,你访问该阵列(在这种情况下)的方法是什么?还是应该只需要直接访问阵列?

When creating getters and setters should you also use those same accessor properties as your way of accessing that array (in this case)? Or should you just access the array directly?

我现在用的访问从类中遇到的问题是,我得到无限循环的调用类会在Data.array一些信息,吸气发现阵列空,所以去从文件中获取它,该函数结束调用吸气剂从内部数据再次,阵列再次空,我们是滞留在一个无限循环。

The problem I am having using the accessors from within the class is that I get infinite loops as the calling class looks for some info in Data.array, the getter finds the array null so goes to get it from the file, and that function ends up calling the getter again from within Data, array is once again null, and we're stuck in an infinite loop.

编辑:

那么,有没有这方面的官方立场?我看到了智慧,在不使用访问者在他们的文件访问,但有些你说的话总是使用访问从一个类中,和其他人都在说永远不要使用访问从与类......... ...................................

So is there no official stance on this? I see the wisdom in not using Accessors with file access in them, but some of you are saying to always use accessors from within a class, and others are saying to never use accessors from with the class............................................

推荐答案

我同意krosenvold,并希望推广他的建议了一下:

I agree with krosenvold, and want to generalize his advice a bit:

不要使用属性的getter和setter昂贵的操作,就像读一本文件或访问网络。对于昂贵的操作使用显式函数调用。

Do not use Property getters and setters for expensive operations, like reading a file or accessing the network. Use explicit function calls for the expensive operations.

通常情况下,类的用户不会想到,一个简单的属性检​​索或转让可能需要大量的时间。

Generally, users of the class will not expect that a simple property retrieval or assignment may take a lot of time.

这还建议微软的框架设计准则;。

不要使用的方法,而不是一个   财产,在下列情况下

Do use a method, rather than a property, in the following situations.

的操作是数量级   比字段集慢会。如果   你甚至考虑提供   的操作的异步版本   以避免阻塞线程,它是   很可能的是,操作太   昂贵是一个属性。在   特别是,操作访问   网络或文件系统(比其他   一次初始化)应该最   有可能是方法,而不是属性。

The operation is orders of magnitude slower than a field set would be. If you are even considering providing an asynchronous version of an operation to avoid blocking the thread, it is very likely that the operation is too expensive to be a property. In particular, operations that access the network or the file system (other than once for initialization) should most likely be methods, not properties.