我有一个更新当前时间的TimeNow变量,它工作正常,但今天我发现它没有更新值
private static readonly DateTime _TimeNow= DateTime.UtcNow;
这是变量,但现在TimeNow没有更新值。
答案 0 :(得分:4)
每当您想获得当前时间时,您应该参考DateTime.UtcNow
。
答案 1 :(得分:1)
readonly 关键字是您可以在字段上使用的修饰符。当字段声明包含只读修饰符时,对声明引入的字段的赋值只能作为声明的一部分或在同一类的构造函数中出现。
取出readonly,然后再试一次。
编辑:检查此代码;
Class TestClass{
private static DateTime _TimeNow;
private static Timer timer;
public TestClass(){
timer = new Timer();
timer.Interval = 1000;
_TimeNow = DateTime.UtcNow; //don't forget this is a variable and not a timer
timer.Tick = new EventHalndler(timer_tick);
timer.Start();
}
private void timer_tick(object sender, EventArgs e){
_TimeNow = DateTime.UtcNow;
}
答案 2 :(得分:1)
您发布的代码只会为" _TimeNow"田野一次。它不可能再次分配它。
如果您在代码中有其他位置经常为该字段分配新值,那么您的程序将无法编译,因为" readonly"该领域的属性。
是什么让你认为该领域的价值应该改变?你的问题中缺乏这样的细节可能与你迄今为止收到的低票有关。
坦率地说,我质疑这样一个领域的价值。至少,当代码的任何其他部分读取值时,它不会具有正确的值,现在"因此字段名称不正确。答案 3 :(得分:0)
使用:
private static DateTime _TimeNow= DateTime.UtcNow;
而不是:
private static readonly DateTime _TimeNow= DateTime.UtcNow;