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

に(いくつかのリファクタリングを伴う)

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 に答える