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

c# – 什么时候我更喜欢财产而不是方法?

发布时间:2020-12-16 00:22:30 所属栏目:百科 来源:网络整理
导读:什么时候我更喜欢财产而不是方法?因为当我使用属性时,以下代码更易读. string agency = base.GetAgencyDetails();string agency = base.Agency; //I could write same logic in getter of the property. 解决方法 就个人而言,我会遵循 MSDN Guidelines. In
什么时候我更喜欢财产而不是方法?因为当我使用属性时,以下代码更易读.

string agency = base.GetAgencyDetails();

string agency = base.Agency; //I could write same logic in getter of the property.

解决方法

就个人而言,我会遵循 MSDN Guidelines.

In general,methods represent actions and properties represent data. Properties are meant to be used like fields,meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines,consider using a property,rather than a method,because less experienced developers find properties easier to use.

如果你考虑它就很有意义,一种方法更适合于某些可能以某种方式改变数据的东西,并且当你检索一些数据并缓存它时,属性是完美的.

如果您使用显式支持的属性,您甚至可以在转换的情况下将两者结合使用:

private ObjType _myObjWithStringification;
private string _stringRepOfData;

public string StringRepresentation
{
    get {
        if (_stringRepOfData == null) {
            _stringRepOfData = _myObjWithStringification.ToString();
        }
        return _stringRepOfData;
    }
}

Re:您的可维护性评论,我不确定它是否非常有效.如果你要点击F12进入你正在使用的属性的声明,无论如何你都会直接进入getter,就像你使用方法一样去你的方法体.

我不确定假设某个属性不会有任何自定义检索逻辑是安全的.

(编辑:李大同)

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

    推荐文章
      热点阅读