簡體   English   中英

System.Nullable <System.TimeSpan>'不包含'TotalMinutes'的定義

[英]System.Nullable<System.TimeSpan>' does not contain a definition for 'TotalMinutes'

有沒有一種優雅的方法來解決這個錯誤,而不是在if()中檢查.HasValue然后添加Date,例如DateTimeUtcNow.Value?

// Compare nullable date time entity.End with utcnow but only compare up to minute precision
// for time.
//
if ((int)(entity.End - DateTime.UtcNow).TotalMinutes < 0) 
{
   // ASSERT: entity.End < UTCNow (i.e. 12/4/2012 3:56 PM < 12/4/2012 3:57 PM) 
}

錯誤:System.Nullable'不包含'TotalMinutes'的定義

我個人認為這是:

if (entity.End > DateTime.Now.AddMinutes(1))
{
    ...
}

如果entity.End為null,則該條件為false。

我經常發現,與其他日期/時間相比,並將其與TimeSpan (或您正在使用的任何類型)進行比較,計算下限或上限更清晰,並將其與可變日期/時間進行比較。 在這種情況下,它確實干凈利落。

編輯:好的,既然這個問題更清楚一點 ,我就把它寫成:

DateTime now = DateTime.UtcNow;
DateTime lowerBound = new DateTime(now.Year, now.Month, now.Hour, now.Minute,
                                   0, 0, DateTimeKind.Utc);
DateTime upperBound = now.AddMinutes(1);
if (entity.End >= lowerBound && entity.End < upperBound)
{
    ...
}

我懷疑我可能仍然誤解了......

一種選擇是創建一個擴展方法來訪問可空和傳播空值中的值:

public static TOut? Select<T, TOut>(this T? nullable, Func<T, TOut> func) 
    where T : struct 
    where TOut : struct
{
    return nullable.HasValue ? (TOut?)func(nullable.Value) : null;
}

然后你可以這樣做:

if ((entity.End - DateTime.UtcNow).Select(t => t.TotalMinutes) > 1)
{
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM