我是C#的新手.当我遇到这个问题时,我正在编写一些由我工作过的人编写的代码:
if (olderTime.happenedWhen.Ticks > happenedWhen.Ticks)
{
thisIsTrulyNew = false;
}
Run Code Online (Sandbox Code Playgroud)
这两个olderTime.happenedWhen和happenedWhen的类型DateTime.
这是比较DateTime更准确的方法吗?
我知道Ticks代表从0001年1月1日00:00开始的100纳秒间隔.但是为什么在我认为我们可以做的时候进行这种比较:
if (olderTime.happenedWhen > happenedWhen){
thisIsTrulyNew = false
}
Run Code Online (Sandbox Code Playgroud)
滴答比较是否达到了正常比较不会的效果?
D S*_*ley 34
这是比较DateTime更准确的方法吗?
没有丝毫.实际上,这就是>运营商在内部实施的方式.
从.NET参考源:
public static bool operator >(DateTime t1, DateTime t2) {
return t1.InternalTicks > t2.InternalTicks;
}
Run Code Online (Sandbox Code Playgroud)
有人可能认为他们通过跳过一行内部代码并直接进入Ticks房产而变得聪明.实际上,Ticks返回的getter InternalTicks,所以除非它被编译器优化,否则使用Ticks属性会添加两个调用以保存一个调用(这两个调用都不会显着改变性能).
Dir*_*irk 18
operator >for 的实现也DateTime比较了ticks,你可以从这个反汇编的代码(mscorlib.dll,System.DateTime类)中看到:
[__DynamicallyInvokable]
public long Ticks
{
[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
get
{
return this.InternalTicks;
}
}
[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool operator >(DateTime t1, DateTime t2)
{
return t1.InternalTicks > t2.InternalTicks;
}
Run Code Online (Sandbox Code Playgroud)