属性在构造函数中不可用

时间:2017-08-06 07:03:13

标签: c# constructor

dateTime = DateTime.Parse(date);中的日期对象或其他任何内容在构造函数中都不可用,因为它尚未设置。是否可以在构造函数中设置所有这些?

 public class BorrowedItemModel
    {
    public String _id { get; set; }
    public String issuer { get; set; }
    public String issued { get; set; }
    public String issuedname { get; set; }
    public String obj { get; set; }
    public String date { get; set; }
    private DateTime dateTime { get; set; }
    private TimeSpan timeleft { get; set; }
    public string TimeLeftString { get; set; }
    private Timer timer;

    public BorrowedItemModel()
    {
        timer = new Timer(1000*60);
        timer.Elapsed += Timer_Elapsed;
        timer.Enabled = true;
        dateTime = DateTime.Parse(date);
        timeleft = dateTime - DateTime.UtcNow;
    }

    private void Timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        timeleft = timeleft.Subtract(TimeSpan.FromMinutes(1));
        TimeLeftString = timeleft.ToString();
    }
}
// where this is called in another class // 

 model = new BorrowedItemModel { _id = value["_id"].ToString(), date = value["date"].ToString(), issuer = value["issuer"].ToString(), issued = value["issued"].ToString(), issuedname = value["issuedname"].ToString(), obj = value["obj"].ToString() };

1 个答案:

答案 0 :(得分:1)

您可以定义日期属性以更新dateTime属性

public class BorrowedItemModel
    {
    public String _id { get; set; }
    public String issuer { get; set; }
    public String issued { get; set; }
    public String issuedname { get; set; }
    public String obj { get; set; }
    private String _date;
    public String date 
    { get {return _date;} 
      set 
      {
        _date=value;
        dateTime = DateTime.Parse(value);
        timeleft = dateTime - DateTime.UtcNow;
      }
    }
    private DateTime dateTime { get; set; }
    private TimeSpan timeleft { get; set; }
    public string TimeLeftString { get; set; }
    private Timer timer;

    public BorrowedItemModel()
    {
        timer = new Timer(1000*60);
        timer.Elapsed += Timer_Elapsed;
        timer.Enabled = true;
        //dateTime = DateTime.Parse(date);
        //timeleft = dateTime - DateTime.UtcNow;
    }

}