C # Ссылка на объект коллекции динамически? - PullRequest
2 голосов
/ 06 марта 2012

Итак, мне нужно получить динамический доступ к значению свойства класса во время выполнения, но я не могу понять, как это сделать ... есть предложения? Спасибо!

//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 ]

6 голосов
/ 06 марта 2012

Если вы хотите сделать это, вы должны использовать отражение:

int result = (int)OrdersEntity.GetType()
                              .GetProperty("ord_num")
                              .GetValue(OrdersEntity, null);
0 голосов
/ 07 марта 2012

Возможно, это не совсем то, что вы хотите сделать, но попробуйте изменить

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() - единственный способ надежно получить строку в этом случае.

...