【问题标题】:Stack Overflow on Property Setter [duplicate]属性设置器上的堆栈溢出 [重复]
【发布时间】:2014-09-02 19:26:27
【问题描述】:

我在 C# 中有一个具有当前属性的对象。

public DateTime startDate
{
    get 
    {
        string[] ymd = Environment.GetCommandLineArgs()[2].Split('.');
        return new DateTime(Int32.Parse(ymd[2]), Int32.Parse(ymd[1]), Int32.Parse(ymd[0])); 
    }
    set { startDate = value; }
}

但是当我尝试使用这样定义的函数时:

public String Calculate(){
    if (startDate > endDate)
        return "not calculable since the end date can not be before than the start date.";

    while (startDate <= endDate)
    {
        if (startDate.DayOfWeek.ToString()[0] != 'S')
            count++;
        startDate = startDate.AddDays(1);
    }

    return "not implemented yet";

发生堆栈溢出 :) 你能帮我解决这个问题吗?

【问题讨论】:

  • 请注意,这与DateTime 无关。这是您的 setter 的一个简单问题,可以通过使用更好的命名约定来避免。

标签: c# properties setter


【解决方案1】:

你的二传手有一个错误。您试图分配给同一个属性,这是堆栈溢出的原因,因为对属性的每个分配都只是调用它的设置器。

set { startDate = value; }

【讨论】:

  • 没错。 set 访问器自称 ad infinitum
  • 为开始日期创建一个类变量并将其替换为与属性相同的名称
【解决方案2】:

属性在这里设置自身,导致无限循环:

set { startDate = value; }

您需要一个支持字段来保留属性的值,如果尚未设置,则对其进行初始化:

private DateTime? _startDate;

public DateTime startDate {
  get {
    if (!_startDate.HasValue) {
      string[] ymd = Environment.GetCommandLineArgs()[2].Split('.');
      _startDate = new DateTime(Int32.Parse(ymd[2]), Int32.Parse(ymd[1]), Int32.Parse(ymd[0]));
    }
    return _startDate.Value;
  }
  set { _startDate = value; }
}

【讨论】:

  • 谢谢你解决了我的问题:)
猜你喜欢
  • 1970-01-01
  • 2018-02-20
  • 2020-11-14
  • 2019-05-18
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 2012-07-19
相关资源
最近更新 更多