【问题标题】:C# IList iterationC# IList 迭代
【发布时间】:2013-07-05 11:47:38
【问题描述】:

我有一个 IList,其中包含一个包含字段名称、ID、位置、商店、人员和金额的对象。我不想通过为每个属性编写语句来检索所有这些字段的值

例如

  IList<CutDetail> btiCollection;
  btiCollection[0].Id
  btiCollection[0].location

无论如何,我是否可以遍历此列表并检索其字段中的数据,而无需专门说明它们是什么?任何援助将不胜感激。

【问题讨论】:

  • 你想对数据做什么?
  • 你想做什么?有很多场景(序列化、数据绑定)如果使用正确的机制,则不需要指定名称
  • 我只是想将来自这些字段的值放入一个字符串变量中。

标签: c# visual-studio oop


【解决方案1】:

如果要检索项目的所有属性的值,可以使用反射创建检索属性值的函数列表:

List<Person> people = new List<Person>();
people.Add(new Person() {Id = 3, Location = "XYZ"});

var properties = (from prop in typeof (Person).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                    let parameter = Expression.Parameter(typeof (Person), "obj")
                    let property = Expression.Property(parameter, prop) 
                    let lambda = Expression.Lambda<Func<Person, object>>(Expression.Convert(property, typeof(object)), parameter).Compile()
                    select
                    new
                        {
                            Getter = lambda,
                            Name = prop.Name
                        }).ToArray();


foreach (var person in people)
{
    foreach (var property in properties)
    {
        string name = property.Name;
        object value = property.Getter(person);
        //do something with property name / property value combination.

    }
}

也可以使用反射来检索属性值,但是如果您有一个很长的列表/许多属性,这会相当慢并且可能会变得引人注目。

【讨论】:

  • 现在我只需要牢牢把握它在做什么。
【解决方案2】:

使用 List&lt;CutDetail&gt;而不是IList&lt;CutDetail&gt;

【讨论】:

  • 抱歉,IList 比刚性 List 更有弹性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多