代码之家  ›  专栏  ›  技术社区  ›  Phill Duffy

在运行时之前属性未知的匿名类型

  •  2
  • Phill Duffy  · 技术社区  · 15 年前

    我有以下场景,我想创建一个数据报,然后在运行时填充内容。

    我遇到的问题是,因为在创建网格之前,我不知道字段是什么,所以我不知道如何正确设置项源。正如您在下面的代码中看到的,我将字段名作为列添加,然后循环遍历我的项,此时,我希望为每个项创建一个匿名类型,在其中我将属性(称为字段名)设置为字段名值。

    foreach (string fieldName in listViewFieldCollection)
    {
        DataGridTextColumn newColumn = new DataGridTextColumn
                                           {
                                               Header = fieldName,
                                               Binding = new Binding(fieldName)
                                           };
    
        dataGrid.Columns.Add(newColumn);
    }
    
    List<object> list = new List<object>();
    
    foreach (ListItem listItem in listItems)
    {
        foreach (string fieldName in listViewFieldCollection)
        {
            list.Add(new
                         {
                             // I want to be able to dynamically build Anonymous type properties here
                             fieldName = listItem[fieldName]
                         });
        }
    }
    
    dataGrid.ItemsSource = list;
    

    例如。如果有名为“标题”和“链接”的字段,则需要列表。添加(新建

        list.Add(new
                     {
                         Title = listItem["Title"],
                         Link = listItem["Link"]
                     });
    

    但是,如果字段是“经理”、“职务”和“工资”,则应执行如下操作

        list.Add(new
                     {
                         Manager = listItem["Manager"],
                         Title = listItem["Title"],
                         Salary = listItem["Salary"],
                     });
    
    2 回复  |  直到 14 年前
        1
  •  0
  •   Greg Levenhagen    15 年前

    听起来使用反射可以工作。下面的代码可能会帮助您开始。代码段将遍历对象上的所有属性。

            foreach (var currentPropertyInformation in source.GetType().GetProperties())
            {
                if ((currentPropertyInformation.GetGetMethod() == null) || (currentPropertyInformation.GetSetMethod() == null)) 
                    continue;
    
                if (string.Compare(currentPropertyInformation.Name, "Item") != 0) // handle non-enumerable properties
                {
                    // place this snippet in method and yield info?
                }
                else // handle enumerable properties
                {
                }
            }
    
        2
  •  1
  •   Andrey    15 年前

    没有反射或代码生成是不可能的。

    new
                     {
                         Manager = listItem["Manager"],
                         Title = listItem["Title"],
                         Salary = listItem["Salary"],
                     }
    

    转换为具有三个字段的类,然后用几行来设置这些字段。这是编译器生成的代码。所以在运行时你不能这样做。