取得物件的屬性名稱、型別(含Nullable)、值

  • 3623
  • 0

取得物件的屬性名稱、型別(含Nullable)、值

Dotblogs 的標籤: ,

做個筆記。筆記重點是若該屬性是實值型別,又允許 Nullable,則有值和 Null 時,要如何呈現:

Imports System.Reflection

Module Module1

    Sub Main()
        Dim u As User = New User()
        u.Birthday = Now
        GetEntityProperty(u)

        Console.ReadLine()
    End Sub

    ''' <summary>
    ''' Gets the entity property.
    ''' </summary>
    ''' <typeparam name="T"></typeparam>
    ''' <param name="Entity">The entity.</param>
    ''' <info>Author: Leo; Date: 2012/3/7 </info>
    Public Sub GetEntityProperty(Of T)(ByVal Entity As T)
        Dim ObjType As Type = Entity.GetType()
        For Each p As PropertyInfo In ObjType.GetProperties()
            Dim val = p.GetValue(Entity, Nothing)
            Dim valType = If(IsNothing(val), p.PropertyType.Name, val.GetType.Name)
            Console.WriteLine(String.Format("Name = {0}, Type = {1}, value = {2}", _
                                            p.Name, valType, If(IsNothing(val), "Null", val.ToString())))
        Next
    End Sub
End Module

User Class 就不貼出來了,反正就是一個對應 Model 的 Class。

輸出結果:

Name = DataKeys, Type = List`1, value = Null
Name = Name, Type = String, value = Null
Name = Birthday, Type = DateTime, value = 2012/3/7 下午 03:12:36
Name = Age, Type = Int32, value = 0
Name = Pay, Type = Nullable`1, value = Null
Name = Address, Type = String, value = Null
Name = Interests, Type = List`1, value = Null

---------

剛同事說,可不可以就算是 Nullable 的欄位,沒給值一樣能顯示屬性真正的型別。當然可以,調整如下:

    Public Sub GetEntityProperty(Of T)(ByVal Entity As T)
        Dim ObjType As Type = Entity.GetType()
        For Each p As PropertyInfo In ObjType.GetProperties()
            Dim val = p.GetValue(Entity, Nothing)
            'Dim valType As String = If(IsNothing(val), p.PropertyType.Name, val.GetType.Name)
            Dim underlyingType As Type = Nullable.GetUnderlyingType(p.PropertyType)
            Dim valType As String = If(IsNothing(underlyingType), p.PropertyType.Name, underlyingType.Name)
            Console.WriteLine(String.Format("Name = {0}, Type = {1}, value = {2}", _
                                            p.Name, valType, If(IsNothing(val), "Null", val.ToString())))
        Next
    End Sub

指後我在 User Class 裡再多加一個 OnjobDate 的日期欄位,一樣允許 Nullable,不設值,好和 Birthday 區隔。以下為輸出結果:

Name = DataKeys, Type = List`1, value = Null
Name = Name, Type = String, value = Null
Name = Birthday, Type = DateTime, value = 2012/3/7 下午 03:43:31
Name = OnjobDate, Type = DateTime, value = Null
Name = Age, Type = Int32, value = 0
Name = Pay, Type = Decimal, value = Null
Name = Address, Type = String, value = Null
Name = Interests, Type = List`1, value = Null

 

--------
沒什麼特別的~
不過是一些筆記而已