2012-03-06 56 views
2

所以我需要在運行時動態訪問一個類屬性的值,但我不知道如何做到這一點......任何建議?謝謝!所以這裏C#動態引用集合對象嗎?

//Works 
int Order = OrdersEntity.ord_num; 

//I would love for this to work.. it obviously does not. 
string field_name = "ord_num"; 
int Order = OrdersEntity.(field_name); 

OK是我到目前爲止與反思,這不太願意除非它通過循環回收項目是一個字符串:

void RefreshGrid(EntityCollection<UOffOrdersStgEcommerceEntity> collection) 
     { 
      List<string> col_list = new List<string>(); 

      foreach (UOffOrdersStgEcommerceEntity rec in collection) 
      { 
       foreach (System.Collections.Generic.KeyValuePair<string, Dictionary<string, string>> field in UOffOrdersStgEcommerceEntity.FieldsCustomProperties) 
       { 

         if (!string.IsNullOrEmpty((string)rec.GetType().GetProperty(field.Key).GetValue(rec, null))) 
         { 
          if (!col_list.Contains<string>((string)rec.GetType().GetProperty(field.Key).GetValue(rec, null))) 
           col_list.Add((string)rec.GetType().GetProperty(field.Key).GetValue(rec,null)); 
         } 

       } 

       foreach (string ColName in col_list) 
       { 
        grdOrders.Columns.Add(new DataGridTextColumn 
        { 
         Header = ColName, 
         Binding = new Binding(ColName) 
        }); 
       }    
      } 

      grdOrders.ItemsSource = collection; 
     } 

回答

6

如果你想做到這一點,你必須使用反射:

int result = (int)OrdersEntity.GetType() 
           .GetProperty("ord_num") 
           .GetValue(OrdersEntity, null); 
+0

所以我基本上有一個屬性的集合,這可能是字符串,小數,日期等我基本上想動態地添加網格列在WPF應用程序中,如果值不爲空。這是我目前爲止的內容,如果所有的集合對象都是字符串,但是它們不是這樣,那麼這是有效的。集合對象是在我下一個回覆中的llblgen集合btw ..代碼。 – diamondracer 2012-03-06 19:06:08

+0

我編輯了我的問題以上我到目前爲止... – diamondracer 2012-03-06 19:13:24

0

它可能不是正是你想做的事,但嘗試改變

if (!string.IsNullOrEmpty((string)rec.GetType().GetProperty(field.Key).GetValue(rec, null))) 
{ 
    if (!col_list.Contains<string((string)rec.GetType().GetProperty(field.Key).GetValue(rec, null))) 
    col_list.Add((string)rec.GetType().GetProperty(field.Key).GetValue(rec,null)); 
} 

到(有一些重構)

string columnValue = rec.GetType().GetProperty(field.Key).GetValue(rec, null).ToString(); 
if (!string.IsNullOrEmpty(columnValue)) 
{ 
    if (!col_list.Contains(columnValue)) 
     col_list.Add(columnValue); 
} 

GetValue()返回Object,所以ToString()是可靠地獲得在這種情況下,字符串的唯一途徑。