环境:的Visual Studio 2015年空条件操作可空的DateTimeOffset
区::UTC + 7:00,曼谷
问题:在可空的DateTimeOffset varialbe(?的DateTimeOffset)时,使用NULL条件运算符会导致异常,即它仍然调用该方法,即使该值为NULL,即(值为DateTimeOffset?)?ToLocalTime(),它将调用ToLocalTime并导致异常。
查询:我可以不使用空有条件的经营者或使用GetValueOrDefault,而不是运营商的解决这个问题,但我想知道为什么它在所有UTC +时区异常resutls,它与UTC效果很好 - 时区
代码:
var dateTimeMinimum = DateTime.MinValue;
var value = (object)dateTimeMinimum; // Mimic the WPF converter behavior
var a1 = value as DateTimeOffset?; // This works
if (a1 != null)// This works as it won't execute the code in the 'if'loop
{
var b1 = (a1 as DateTimeOffset?)?.ToLocalTime();
}
var dto = (value as DateTimeOffset?)?.ToLocalTime() ?? (DateTime)value;// This breaks with following exception
编辑:
我知道有很多方法来修复代码,即
DateTime dateTimeMinimum = DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc);
这里是我的查询不过,当我不使用空条件操作
var a1 = value as DateTimeOffset?;
它不导致异常。难道是因为空条件运算符每解开变量以下博客
http://www.ninjacrab.com/2016/09/11/c-how-the-null-conditional-operator-works-with-nullable-types/
我更感兴趣的是理解为什么它打破了,当我用空条件运算符和作品时,我如果使用“作为”操作简单的投不使用DateTimeKind.Utc
EDIT2:
这是的DateTimeOffset(.NET框架代码)的构造和它打破在ValidateOffset方法。 来源 - http://referencesource.microsoft.com/#mscorlib/system/datetimeoffset.cs,68b4bb83ce8d1c31
// Constructs a DateTimeOffset from a DateTime. For Local and Unspecified kinds,
// extracts the local offset. For UTC, creates a UTC instance with a zero offset.
public DateTimeOffset(DateTime dateTime) {
TimeSpan offset;
if (dateTime.Kind != DateTimeKind.Utc) {
// Local and Unspecified are both treated as Local
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
else {
offset = new TimeSpan(0);
}
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(dateTime, offset);
}
抛出异常时偏移的值是多少?错误消息似乎表明结果的年份是小于0或大于10K – pquest
DateTime.MinValue –
这是偏移量的值? – pquest