【问题标题】:C# Reference collection object dynamically?C#动态引用集合对象?
【发布时间】:2012-03-24 05:16:11
【问题描述】:

所以我需要在运行时动态访问类属性的值,但我不知道该怎么做……有什么建议吗?谢谢!

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

【问题讨论】:

    标签: c# reflection dynamic llblgen


    【解决方案1】:

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

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

    【讨论】:

    • 所以我基本上有一个属性集合,可能是字符串、小数、日期等,如果值不为空,我基本上想在 WPF 应用程序中动态添加网格列。到目前为止,这是我所拥有的,如果所有集合对象都是字符串,则它可以工作,但它们不是。集合对象是一个 llblgen 集合 btw.. 代码在我的下一个回复中。
    【解决方案2】:

    这可能不是你想要做的,但尝试改变

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      相关资源
      最近更新 更多