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() };
答案 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;
}
}