为什么我的get / set实现会产生堆栈错误?

时间:2012-08-25 08:48:33

标签: c#

我在C#中尝试以下内容:

public class Reference : AuditableTable
    {
        [Range(0, 99, ErrorMessage = "{0} must be between {1} and {2}")]
        [DisplayName("Order")]
        public int Order {
                get { return Order; }
                set {
                    if ((value < 0) || (value > 99)) {
                        throw new Exception(string.Format("{0} must be between 0 and 99", value.ToString()));
                    } else {
                        Order = value;
                    }
                }
            }

有人可以帮助解释为什么这会在阅读时出现堆栈溢出错误吗?

4 个答案:

答案 0 :(得分:8)

您的属性正在引用自身,从而导致无限循环。
一个明显的解决方法是使用私有字段并通过您的属性公开它:

private int order;
public int Order
{
   get
   {
      return order; //private field
   }
   set
   {
      if ((value < 0) || (value > 99)) {
               throw new Exception(string.Format("{0} must be between 0 and 99",    
                                     value.ToString()));
      } else {
          order = value; // again accessing the private field (setting this time)
      }
   }
}

答案 1 :(得分:3)

问题在于这一行:

get { return Order; }

这是递归调用属性,导致堆栈溢出。

答案 2 :(得分:1)

setter和getter都引用自身导致Stack Overflow。修复如下:

private int _order;

public int Order {
    get { return _order; }
    set {
        if ((value < 0) || (value > 99)) {
            throw new Exception(string.Format("{0} must be between 0 and 99", value.ToString()));
        } else {
            _order = value;
        }
    }
}

答案 3 :(得分:0)

int _order;
public int Order {
    get { return _order; }
    set {
        if ((value < 0) || (value > 99)) {
            throw new Exception(string.Format("{0} must be between 0 and 99", value.ToString()));
        } else {
            _order = value;
        }
    }
}