加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 你应该从类中使用访问器属性,还是从类外面使用?

发布时间:2020-12-15 04:01:16 所属栏目:百科 来源:网络整理
导读:参见英文答案 What is the best way to access properties from the same class,via accessors or directly? [closed]5个 我有一个’Data’类,它使用一个getter来访问一些数组.如果数组为空,那么我希望Data访问该文件,填写数组,然后返回特定的值. 现在这是我
参见英文答案 > What is the best way to access properties from the same class,via accessors or directly? [closed]5个
我有一个’Data’类,它使用一个getter来访问一些数组.如果数组为空,那么我希望Data访问该文件,填写数组,然后返回特定的值.

现在这是我的问题:

当创建getter和setter时,您还应该使用与访问该数组的方式相同的访问器属性(在这种情况下)?还是应该直接访问数组?

我正在使用类中的访问器的问题是,我得到无限循环,因为调用类在Data.array中查找一些信息,getter找到数组null,以便从文件中获取它,该函数结束再次从Data中调用getter,数组再次为null,我们被困在一个无限循环中.

编辑:

那么没有官方的立场呢?我看到智慧没有使用他们的文件访问访问者,但有些人说总是使用访问者从一个类,而其他人则说永远不会使用访问者与类……… ……………………………..

解决方法

我同意krosenvold的意思,想要概括一下他的建议:

不要使用Property getter和setter来执行昂贵的操作,比如读取文件或访问网络.对昂贵的操作使用显式函数调用.

通常,类的用户不会期望简单的属性检索或分配可能需要很多时间.

This is also recommended in Microsoft’s Framework Design Guidelines.;

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读