[英]How to use reflection to get/set the value of a property?
我試圖使用反射來循環給定類中的所有屬性,並對發現的所有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
}
}
問題似乎是您要傳遞給GetValue
的參數-它必須是myObj
,而不是this
。
另外,您需要將調用的結果DateTime?
為DateTime?
分配:
DateTime? test = (DateTime?)prop.GetValue(this);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.