2012-04-22 40 views
1

我有一个结构中的DateTime属性字段。我正在尝试验证输入日期以确保输入的值不在将来。StackOverflowException当比较日期

我使用下面的代码:

public struct Car 
{ 
    public DateTime Year 
    { 
     get 
     { 
      return Year; 
     } 

     set 
     { 
      if (value > DateTime.Now) 
       throw new InvalidOperationException("Date cannot be in the futrure"); 
      else 
       Year = value; 
     } 
    } 
} 

现在当我尝试运行此代码,我不断收到一个StackOverflowException与消息,因为当前线程堆栈溢出状态“无法计算表达式。 “

关于这是为什么,或者如何解决这个问题的任何想法?

- 谢谢。

+0

你能给出一个很好的使用struct的理由吗? – ChaosPandion 2012-04-22 04:37:42

+0

@ChaosPandion http://stackoverflow.com/questions/203695/structure-vs-class-in-c-sharp – 2012-04-22 04:44:11

+1

@Jeremy Thompson - 我很确定我在某个时候读过这个问题。我的意图实际上是理解他们为什么选择使用它。 – ChaosPandion 2012-04-22 04:46:48

回答

4

你调用一个名为Year财产,其get访问调用Year,其get访问调用Year ......等等,等等,直到你的堆栈溢出。

您应该创建一个专用字段private DateTime _year来存储实际值。

4

它正在返回自己......尝试设置一个变量。

public struct Car 
{ 
    private DateTime _year; 
    public DateTime Year 
    { 
     get 
     { 
      return _year; 
     } 

     set 
     { 
      if (value > DateTime.Now) 
       throw new InvalidOperationException("Date cannot be in the futrure"); 
      else 
       _year = value; 
     } 
    } 
}