2

所以我需要在运行时动态访问类属性的值,但我不知道如何做到这一点......有什么建议吗?谢谢!

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

2 回答 2

6

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

int result = (int)OrdersEntity.GetType()
                              .GetProperty("ord_num")
                              .GetValue(OrdersEntity, null);
于 2012-03-06T17:19:13.613 回答
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));
}

to(进行一些重构)

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

于 2012-03-06T20:47:13.923 回答