TimeSpan.Duration()
将为您提供TimeSpan持续时间的绝对值,这在某些情况下非常有用.
然而,它是方法而不是结构的属性. the MSDN guidelines on choosing a method or a property的第一段规定:
In general, methods represent actions and properties represent data.
Properties are meant to be used like fields, meaning that properties
should not be computationally complex or produce side effects. When it
does not violate the following guidelines, consider using a property,
rather than a method, because less experienced developers find
properties easier to use.Consider using a property if the member represents a logical attribute of the type.
(强调他们的.)
持续时间似乎也没有违反“使用方法”部分.
我认为这可能是出于向后兼容的原因,所以我去了back to the property vs method guidelines for .NET 2,它们相对没有变化.那么我想知道.NET 1.1是否只是没有属性,but it did,所以我认为这也不是原因.
解决方法:
我猜这是因为它可以在边界情况下抛出OverflowException.通常情况下,属性getter最好不要抛出异常(在某些情况下可能除了ObjectDisposedException),尽管我不知道具体说明这一点的指南.这可能会在“产生副作用”指南中涵盖,因为抛出的异常肯定是副作用.