【问题标题】:If I fill a GridView with anonymous objects, how can i get their properties?如果我用匿名对象填充 GridView,如何获取它们的属性?
【发布时间】:2010-10-20 14:22:54
【问题描述】:

我有一个通过 LINQ 表达式填充的 GridView。
像这样的:

GridView1.DataSource = from c in customers, o in c.Orders, 
  total = o.Total where total >= 2000 select new {id = c.CustomerID, 
  order = o.OrderID, total = total};

在它的 RowCreated 方法中,我尝试获取一个属性,例如 id,但它没有已知类型:

object element = e.Row.DataItem;
int id = element.id; // It's bad!!!!!!

我该怎么办?
谢谢!!

【问题讨论】:

    标签: asp.net linq gridview


    【解决方案1】:

    为你的类型命名!

    public class GridType
    {
        public int Id {get; set:} . . etc
    }
    

    然后在 linq 中,

    . . . select new GridType {...etc}
    

    然后在 RowCreated 方法中,将数据项转换为 GridType,您可以访问它的属性。

    否则你会寻找 C# 不做的鸭子类型。

    【讨论】:

      【解决方案2】:

      你需要使用反射。

      Type t = element.GetType();
      int id = 0;
      
      foreach (PropertyInfo p in t.GetProperties())
      {
          // Not very nice but finds an integer property called "id"
          if (p.PropertyType == typeof(int) && p.Name == "id")
          {
             id = (int)p.GetValue(element, null);
          }
      }
      

      使用 Linq:

      Type t = element.GetType();
      int id = 0;
      var pt = new List<PropertyInfo>();
      pt.AddRange(t.GetProperties());
      id = (int)pt.Where(p => p.PropertyType == typeof(int) && p.Name == "id").First().GetValue(element, null);
      

      但不确定它读起来是否更好,尤其是 Type.GetProperties 返回一个数组,该数组必须转换为 List 才能获取 Linq 方法。

      【讨论】:

        【解决方案3】:

        如果您想使用匿名对象,这是您必须付出的代价:当您离开声明对象的范围时,您会失去强类型。我建议明确声明您的类型,除非您想使用 DataBinder.Eval...

        【讨论】:

          猜你喜欢
          • 2014-10-15
          • 2019-06-13
          • 1970-01-01
          • 1970-01-01
          • 2013-02-19
          • 2011-11-06
          • 1970-01-01
          • 1970-01-01
          • 2022-08-23
          相关资源
          最近更新 更多