通过字符串路径获取对象的属性值

Public Function GetProperty(objInput As Object, proString As String, Optional delimiter As String = "_") 
  Dim proPath As String() = Split(proString, delimiter), objLoc As Object = objInput 
  For Each p As String In proPath 
    If objLoc.GetType.GetProperty(p) Is Nothing Then ' property p not found, return null 
      objLoc = DBNull.Value : Exit For 
    Else 
      If IsNothing(objLoc.GetType.GetProperty(p + "Specified")) Then ' property specified for some kinds of data objects 
        If objLoc.GetType.GetProperty(p).GetValue(objLoc) Is Nothing Then ' property p is nothing, return null 
          objLoc = DBNull.Value : Exit For 
        ElseIf objLoc.GetType.GetProperty(p).GetValue(objLoc).GetType.BaseType.Name = "CollectionBase" Then ' property p is a collection, return the first child 
          If objLoc.GetType.GetProperty(p).GetValue(objLoc).Count = 0 Then ' property p is an empty collection, return null 
            objLoc = DBNull.Value : Exit For 
          Else 
            objLoc = objLoc.GetType.GetProperty(p).GetValue(objLoc).Item(0) 
          End If 
        Else 
          objLoc = objLoc.GetType.GetProperty(p).GetValue(objLoc) 
        End If 
      ElseIf objLoc.GetType.GetProperty(p + "Specified").GetValue(objLoc) Then 
        If objLoc.GetType.GetProperty(p).GetValue(objLoc) Is Nothing Then ' property p is nothing, return null 
          objLoc = DBNull.Value : Exit For 
        ElseIf objLoc.GetType.GetProperty(p).GetValue(objLoc).GetType.BaseType.Name = "CollectionBase" Then ' property p is a collection, return the first child 
          If objLoc.GetType.GetProperty(p).GetValue(objLoc).Count = 0 Then ' property p is an empty collection, return null 
            objLoc = DBNull.Value : Exit For 
          Else 
            objLoc = objLoc.GetType.GetProperty(p).GetValue(objLoc).Item(0) 
          End If 
        Else 
          objLoc = objLoc.GetType.GetProperty(p).GetValue(objLoc) 
        End If 
      Else 
        objLoc = DBNull.Value : Exit For 
      End If 
    End If 
  Next 
  Return objLoc 
End Function

  

猜你喜欢

转载自www.cnblogs.com/simeut/p/9265652.html
今日推荐