如果我这样做:
var foo = new Foo
{
Created = DateTime.Now,
Modified = DateTime.Now
};
是否有任何机会进行任何编译器优化,以确保两个日期属性相同,或者我必须首先将Now
读入临时变量?
答案 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
如果单独初始化的概率相当高。我的系统上的以下循环(在DEBUG
和RELEASE
中)永远不会超过几千次迭代。
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;
}
}