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

用户名

我知道在Stack Overflow上有很多关于此主题的问题,但是我找不到对当前情况的任何具体答案。

  1. 我有一个动态生成的行集合。
  2. 属性名称(列和列数)仅在运行时知道。
  3. 我有以下代码,

    // 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 */
    }
    
  4. 我用下面的代码调用上述方法,

    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).
    );
    

在Stack Overflow上曾多次问过相同的问题,但是仅当您知道属性名称时,解决方案才是

  1. 通过字符串从C#动态对象获取属性值(反射?)
  2. 如何在C#中访问匿名类型的属性?//仅当预先知道属性名称时才能访问属性。

任何帮助是极大的赞赏!

thepirat000

获取第一项,将其强制转换为object,然后可以获得属性:

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

要不就:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章