2014-02-28 7 views
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 

어떤 생각이나 제안이 있으십니까?

감사합니다.

마지막으로 반환 할 때 문제가 발생합니다. "정수 유형의 값이 T를 입력 coverted 수 없습니다":

Select Case defaultVal.GetType() 
    Case GetType(Integer) 
     Return CType(nodeValue, Integer) 
End Select 

답변

3

당신이 저장하는 경우 그것은 내가 아래 시나리오를 시도하고 내가 오류가

을 "nodeValue를가 T를 입력 변환 할 수 없습니다"라는 이전의 객체로서의 값, 작동 :

Sub Main() 
    Dim myInt = Foo(Of Integer)("123") 
End Sub 

Function Foo(Of T)(input As String) As T 
    Dim bar As Object = input 
    Return CType(bar, T) 
End Function