首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在不同的词法作用域中声明和设置DateTime对象的值?

如何在不同的词法作用域中声明和设置DateTime对象的值?
EN

Stack Overflow用户
提问于 2012-09-18 00:44:02
回答 1查看 113关注 0票数 0

我读到了这个问题和答案,其中如果需要修改(或转换)对象的时间,必须创建一个新的DateTime对象,因为DateTime是一个不可变的对象类型。

Why DateTime.AddHours doesn't seem to work?

如果声明了变量,并且在相同的词法作用域中设置了一个值,那么这是很好的。除非我在不同的词法作用域中声明和设置值。通常我会执行"DateTime from_instant = null;“,这样它至少有一个值,这样我就可以在设置它之后使用它。但是,使用DateTime时,一旦设置了值,它就是不可变的。那么,如何通过执行"from_instant.AddHours(-10);“来调整对象的值呢?例如,在声明它的词法范围之外?

在我下面的例子中,每当我重置"from_instant“时,它都不会改变。我希望能够改变它。由于该值是不可变的,通常如何重置该值?

代码语言:javascript
复制
    DateTime from_instant = DateTime.Now;

    bool set_scan_start_instant_to_last_scan_instant = Convert.ToBoolean(GetConfig("set_scan_start_instant_to_last_scan_instant"));

    if (set_scan_start_instant_to_last_scan_instant)
    {
        from_instant = GetScanTimeFromFile(@".\last_scan_instant.txt");
        from_instant = DateTime.Now;
    }
    else
    {
        if (!string.IsNullOrEmpty(scan_interval_minutes))
        {
            from_instant = DateTime.Now.AddMinutes(Convert.ToInt32(scan_interval_minutes));
        }
        else if (!string.IsNullOrEmpty(scan_interval_hours))
        {
            from_instant = DateTime.Now.AddHours(Convert.ToInt32(scan_interval_hours));
        }
        else if (!string.IsNullOrEmpty(scan_interval_days))
        {
            from_instant = DateTime.Now.AddDays(Convert.ToInt32(scan_interval_days));
        }
    }

    DateTime to_instant = DateTime.Now;
    WriteScanTimeToFile(@".\last_scan_instant.txt", to_instant.ToString());

    Console.WriteLine("from_instant: " + from_instant.ToString());  
    Console.WriteLine("to_instant: " + to_instant.ToString());        
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-18 00:45:48

问题是您一直在调用DateTime上的方法,而忽略返回值。别干那事。

更改此设置:

代码语言:javascript
复制
from_instant.AddHours(Convert.ToInt32(scan_interval_hours));

代码语言:javascript
复制
from_instance = from_instant.AddHours(Convert.ToInt32(scan_interval_hours));

或者:

代码语言:javascript
复制
fromInstance += TimeSpan.FromHours(Convert.ToInt32(scan_interval_hours));

(等)。不清楚为什么你似乎认为你不能这样做。也不清楚您希望这段代码做什么:

代码语言:javascript
复制
from_instant = GetScanTimeFromFile(@".\last_scan_instant.txt");
from_instant = DateTime.Now;

为什么要为from_instant赋值,然后立即赋值呢?

(附注:下划线在C#代码中非常简单。)

在我下面的例子中,每当我重置"from_instant“时,它都不会改变。

听起来您可能没有正确地诊断问题。改变变量的值确实会改变它...

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12463710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档