c# - 为什么我们需要 C# 属性中的支持字段?

标签 c# properties field

注意:不是关于自动实现属性的问题。自动实现的属性是关于在 getter 和 setter 中没有逻辑的属性,而我在我的代码中非常清楚地声明有一些逻辑。这不是 this question 的副本两者都不是,因为问题确实不同,答案也是如此。


我看到了很多这样的:

private int _age;
public int Age
{
    get
    {
        if(user.IsAuthorized)
        {
            return _age;
        }
    }
    set
    {
        if(value >= 0 && value <= 120)
        {
            _age = value;
        }
        else
        {
            throw new ArgumentOutOfRangeException("Age","We do not accept immortals, nor unborn humans...");
        }
    }
}

但为什么我们需要支持字段?为什么不归还属性(property)本身?

public object Age
{
    get
    {
        if(user.IsAuthorized)
        {
            return Age;
        }
    }
    set
    {
        if(value >= 0 && value <= 120)
        {
            Age = value;
        }
        else
        {
            throw new ArgumentOutOfRangeException("Age","We do not accept immortals, nor unborn humans...");
        }
    }
}

最佳答案

好吧,返回属性本身会导致堆栈溢出异常:

public object Property 
{
    get
    {
        return Property;
    }
    set
    {
        Property = value;
    }
}

想象

  MyObject o = new MyObject();

  // cause Stack Overflow exception
  o.Property = null;

原因很简单:

  1. 设置 Property = null 调用 set
  2. 调用 Property = value; 进而调用 set
  3. 调用 Property = value;...等等。

因此,如果属性存储一些值,则该值应存储在字段(您需要一个字段)中,我们不能使用属性来存储本身。如果您想缩短代码,请这样写(自动属性):

  public object Property { 
    get; // let .Net create a backing field for you
    set;
  }

关于c# - 为什么我们需要 C# 属性中的支持字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37431888/

相关文章:

objective-c - 如何将 NSString 从一个 View Controller 传递到另一个 View Controller ?

c# - 如何获取枚举的属性

c# - 条件 DataGridView 到 DataTable 的转换

c# - MSAcpi_ThermalZoneTemperature 类不显示实际温度

javascript - 是否可以在 ExtJS 中将存储字段标记为只读?

python - 属性应该进行重要的初始化吗?

MySQL 无法识别虚拟列/字段

json - MongoDB 指南针 : How to select Distinct Values of a Field

c# - iTextSharp 中的克罗地亚语字母

c# - 如何在 C# 中读取 app.config 中的自定义配置部分