環境:的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