用PropertyInfo一口氣列出所有peoperty

今天在幫前人留下來的code作debug時

因為前人的code寫的還不錯,都包得好好的

所以比較不方便去找包好的物件中有哪些property


今天在幫前人留下來的code作debug時

因為前人的code寫的還不錯,都包得好好的

所以比較不方便去找包好的物件中有哪些property

而且我也懶得一個一個輸出來檢查

直覺就想到要用Reflection來解決

就跑到MSDN查一下

原來要這樣寫


DataClassesDataContext ctx = new DataClassesDataContext();
Employees emp = ctx.Employees.First();
foreach (PropertyInfo item in typeof(Employees).GetProperties()) {
    Response.Write(String.Format("name : {0}, Value : {1}<br/>", item.Name, item.GetValue(emp, null)));
}

這邊先用LINQ to SQL的類別做sample

這個小技巧在debug實蠻好用的


DataClassesDataContext ctx = new DataClassesDataContext();
Employees emp = ctx.Employees.First();
var pros = typeof(Employees).GetProperties().Cast<PropertyInfo>();
foreach (var item in pros) {
    Response.Write(String.Format("name : {0}, Value : {1}<br/>", item.Name, item.GetValue(emp, null)));
}

LINQ版

另外剛剛看到用TypeDescriptor的寫法也不錯,可以依實際情況來操作

Reflection應用於Linq更新

TypeDescriptor 類別