0
我遇到了返回類型「T」值的麻煩。這是更容易顯示,而不是解釋所以這裏是方法:從函數返回一個通用函數類型的值
Protected Function GetElementValue(Of T)(ByVal nodeName As String, Optional missingIfNotExists As Boolean = True,
Optional missingIfEmpty As Boolean = True,
Optional ByRef defaultVal As T = Nothing,
Optional maxLength As Integer = Nothing) As T
'Set up the node to get the value from
Dim node = xmlRoot.SelectSingleNode(nodeName)
Select Case True
Case IsNothing(node) 'If the node is missing from the xml document
'Add the node to the misssing elements array if missingIfNotExists = True
If missingIfNotExists Then missingElements.Add(nodeName)
'Return the default value
Return defaultVal
Case node.InnerText.Trim.Length = 0 'The node exists in the xml document but has no value
'Add it to missing elements if missingIfEmpty = True
If missingIfEmpty Then missingElements.Add(nodeName)
'If there is a default value passed in, return that value
Return defaultVal
Case Else 'The node exists and contains data
End Select
'The element exists and contains data
Dim nodeValue = node.InnerText.Trim
'If a size constraint was passed in, ensure the element data is not too long. Shorten the string if it is
If Not IsNothing(maxLength) AndAlso nodeValue.Length > maxLength Then nodeValue = nodeValue.Substring(0, maxLength)
Return CType(nodeValue, T)
End Function
任何想法或建議?
謝謝。
最後的回報是我遇到問題的地方。它說「的nodeValue不能被轉換爲T類型」
我曾嘗試下面的場景,我得到的錯誤:「整型的值不能coverted鍵入T」:
Select Case defaultVal.GetType()
Case GetType(Integer)
Return CType(nodeValue, Integer)
End Select