属性支持字段 - 这是什么好处? [英] Properties backing field - What is it good for?

查看:152
本文介绍了属性支持字段 - 这是什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一方面,我知道属性的建议用法是有一个后备字段,如下面的例子:

On one hand, I know that the advisable usage of Properties is to have a backing field, like in the following example:

    private int m_Capacity;

    public int Capacity
    {
        get { return m_Capacity > 0 ? m_Capacity : -666; }
        set { m_Capacity = value; }
    }

在另一方面,我利用上面的例子中得到什么好处在丢弃现场,并在下面的例子中只使用属性为所有目的,如:

On the other hand, what benefit do I get from using the above example over discarding the field and using only the property for all purposes, like in the following example:

    public int Capacity
    {
        get { return Capacity > 0 ? Capacity : -666; }
        set { Capacity = value; }
    }

什么是好有关使用支持字段为常规(非自动实施)属性?

What is good about using a backing field for regular (non-auto-implemented) properties?

推荐答案

如果你这样做:

public int Capacity 
{ 
    get { return Capacity > 0 ? Capacity : -666; } 
    set { Capacity = value; } 
}



你的代码将有无限递归。它永远不会工作。这是因为容量的吸气剂本身引用。同样的事情会发生的制定者。

then your code will have an infinite recursion. It will never work. That's because the getter for Capacity is referencing itself. Same thing goes for the setter.

除非你使用自动属性,你需要一个支持字段

Unless you are using automatic properties, you need a backing field

这篇关于属性支持字段 - 这是什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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