如何使用反射从动态(匿名类型)对象获取属性?

时间:2014-02-13 04:00:40

标签: c# generics dynamic properties anonymous-types

我知道这个主题在stackoverflow上有很多问题,但我找不到任何具体的答案来解决我的现状。

  1. 我有一个动态生成的行集合。
  2. 属性名称(列和列数)仅在运行时已知。
  3. 我有以下代码,
  4. // collection gets populated at run time, the type T is dynamic.
    public void GenerateExcel<T>(string filename, IEnumerable<T> collection)
    {
        // Since the T passed is dynamic Type I am facing issues in getting
        // the property names.
        var type = typeof(T); // the type T is an anonymous type, and thus
                              // the 'type' variable is always an Object type.
        var columns = type.GetProperties().Length; // when I run this line it
                                                   // is obvious the properties 
                                                   // returned is always 0 so how
                                                   // do I get the properties?
    
        /* Implementation omitted */
    }
    
    1. 我使用下面的代码调用上述方法
    2. GenerateExcel<dynamic>(
       "filename.xls",
       new[] { 
        new { Obj1 = "a", Obj2 = 1, Obj3 = 3.1, Obj4 = new DateTime(2014, 1, 1) }, 
        new { Obj1 = "b", Obj2 = 2, Obj3 = 3.2, Obj4 = new DateTime(2014, 1, 2) },
        new { Obj1 = "c", Obj2 = 3, Obj3 = 3.3, Obj4 = new DateTime(2014, 1, 3) },
        new { Obj1 = "d", Obj2 = 4, Obj3 = 3.4, Obj4 = new DateTime(2014, 1, 4) },
       }); // these objects (Obj1, Obj2 ... (columns) are generated dynamically at run time).
      

      同样的问题被多次询问,这里是stackoverflow,但解决方案只有在您知道属性名称时才会出现,例如

      1. Get property value from C# dynamic object by string (reflection?)
      2. How to access property of anonymous type in C#? //只有在提前知道属性名称时才能访问该属性。
      3. 非常感谢任何帮助!

2 个答案:

答案 0 :(得分:5)

获取第一个项目,将其转换为 object ,然后您可以获取属性:

object e = collection.FirstOrDefault();
var columns = e.GetType().GetProperties().Length;

或者只是:

collection.FirstOrDefault().GetType().GetProperties().Length;

答案 1 :(得分:0)

你能用吗?

 dynamic dy = obj;
 Console.WriteLine(dy.param);