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

dia*_*cer 2 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);
Run Code Online (Sandbox Code Playgroud)

好的,所以这里是我到目前为止的反射,除非它循环的集合项是一个字符串:

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;
        }
Run Code Online (Sandbox Code Playgroud)

eou*_*3hf 6

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

int result = (int)OrdersEntity.GetType()
                              .GetProperty("ord_num")
                              .GetValue(OrdersEntity, null);
Run Code Online (Sandbox Code Playgroud)