簡體   English   中英

空字符串的怪異情況

[英]Weird situation with Empty String

僅當String不為null或為空時,我才具有解析日期字段的代碼,但出現以下異常

從字符串“”到類型“日期”的轉換無效。

說明:執行當前Web請求期間發生未處理的異常。 請查看堆棧跟蹤,以獲取有關錯誤及其在代碼中起源的更多信息。

異常詳細信息:System.InvalidCastException:從字符串“”到類型“日期”的轉換無效。

源錯誤:

Line 29:         
Line 30:  If (Not String.IsNullOrEmpty(last_login)) Then 
Line 31:    If  String.Format("{0:MM/dd/yy H:mm:ss}", last_login) < Now.AddMinutes(-5) Then
Line 32:      Return "height:100%;width:100% ;background-color:#FF0000;font-weight: bold; color: #000000"
Line 33:    Else

有人請解釋嗎?

" "不是空字符串。 (內部有一個空格。)也許您應該調用.Trim()

last_login != null && last_login.Trim().Length > 0

或者,如果您使用的是.NET 4,則IsNullOrWhitespace甚至更好:

string.IsNullOrWhitespace(last_login)

編輯 ,感謝@Anthony和@Joel。

真是一團糟。 您試圖在字符串上使用日期格式符號,以產生一個字符串,並與日期進行比較。

讓我們嘗試一下。

Dim dLast As DateTime
If ((Not last_login Is Nothing) AndAlso DateTime.TryParse(last_login.Trim(), dLast)) Then
    If (dLast < Now.AddMinutes(-5)) Then
        Return "height:100%;width:100% ;background-color:#FF0000;font-weight: bold; color: #000000"
    End If
End If

編輯:訪問之前檢查null字符串。

似乎您需要String.IsNullOrWhiteSpace() 我在引號內看到一個空格字符。

.TryParse適用於string = none

Dim dLast As DateTime
If DateTime.TryParse(last_login, dLast) Then
    If (dLast < Now.AddMinutes(-5)) Then
        Return "height:100%;width:100% ;background-color:#FF0000;font-weight: bold; color: #000000"
    End If
End If

“”是一個空格,既不為null也不為空。 您可以先Trim()字符串,然后檢查null,Empty或Length == 0。

它不能為null或為空。 這是一個空間。 您可以嘗試修剪它。

暫無
暫無

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

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