2012-03-06 54 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()是可靠地获得在这种情况下,字符串的唯一途径。