3

我正在 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

4 回答 4

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)
      }
   }
}
于 2012-08-25T08:49:21.143 回答
3

问题是这一行:

get { return Order; }

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

于 2012-08-25T08:49:48.200 回答
1

setter 和 getter 都在引用自己导致堆栈溢出。像这样修复它:

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;
        }
    }
}
于 2012-08-25T08:51:25.633 回答
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;
        }
    }
}
于 2012-08-25T08:51:02.217 回答