C#引用动态参考集合对象?

时间:2012-03-06 17:16:52

标签: c# reflection dynamic llblgen

所以我需要在运行时动态访问类属性的值,但我无法弄清楚如何执行此操作...任何建议?谢谢!

//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);

好的,所以这就是我到目前为止所做的反射,除非它循环的集合项是一个字符串,否则它会产生瑕疵:

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;
        }

2 个答案:

答案 0 :(得分:6)

如果你想这样做,你必须使用反射:

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

答案 1 :(得分: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()是在这种情况下可靠获取字符串的唯一方法。