DateTime.Now在对象初始化器中

时间:2016-06-01 22:15:21

标签: c# .net

如果我这样做:

var foo = new Foo
{
    Created = DateTime.Now,
    Modified = DateTime.Now
};

是否有任何机会进行任何编译器优化,以确保两个日期属性相同,或者我必须首先将Now读入临时变量?

1 个答案:

答案 0 :(得分:2)

无论优化如何,编译器都不应省略DateTime.Now。要确保将字段初始化为相同的值,请考虑以下内容:

struct Foo
{
    public DateTime Created;
    public DateTime Modified;
    public Foo(DateTime dt)
    {
        Created = Modified = dt;
    }
}

var foo = new Foo(DateTime.Now);

Created != Modified如果单独初始化的概率相当高。我的系统上的以下循环(在DEBUGRELEASE中)永远不会超过几千次迭代。

for (int i = 0; i < 1000000000; i++)
{
    var foo = new Foo
    {
        Created = DateTime.Now,
        Modified = DateTime.Now
    };
    if (foo.Created != foo.Modified)
    {
        Console.WriteLine("{0} {1} {2}", foo.Created.Ticks, foo.Modified.Ticks, i);
        break;
    }
}