2016-05-17 79 views
1

我正在嘗試使用反射來遍歷給定類中的所有屬性,並對它找到的所有DateTime屬性執行轉換。如何使用反射來獲取/設置屬性的值?

但是我得到一個錯誤{「對象不匹配目標類型。」}

如何獲取給定屬性的值,並將其值?

我的代碼:

var properties = myObj.GetType().GetProperties(); 
foreach (var prop in properties) { 
    if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?)) { 
     DateTime? test = prop.GetValue(this); 
     // Do conversion on test 
     // Do something like prop.SetValue(??) with the new value 
    } 
} 

回答

2

這個問題似乎是要傳遞到GetValue參數 - 它需要myObj,不this

此外,你需要轉換調用的結果DateTime?上分配:

DateTime? test = (DateTime?)prop.GetValue(this); 
+0

應該可以處理日期時間和日期?一起。您可以隨時將值類型T取消爲'可爲空值'。 –

+0

@mikez編輯,謝謝!將一個不可空對象拆分爲一個完全可空的對象。我幾乎可以肯定,我在很久以前嘗試過這種方式,當可空類型出來時,它並不起作用。但也許我做錯了。 – dasblinkenlight

相關問題