比较日期时出现 StackOverflowException

zaz*_*aza 1 c# stack-overflow datetime struct properties

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

我正在使用以下代码:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我现在尝试运行此代码时,我不断收到 StackOverflowException 并显示消息“无法计算表达式,因为当前线程处于堆栈溢出状态”。

关于为什么会这样或者如何解决这个问题有什么想法吗?

-谢谢。

Chr*_*ler 5

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

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; 
        } 
    } 
} 
Run Code Online (Sandbox Code Playgroud)


Avn*_*tan 5

您正在调用一个名为 的属性Year,其get访问器调用Year,其get访问器调用Year...等等,直到堆栈溢出。

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