gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:56:50 26 4
gpt4 key购买 nike

<分区>

我知道在 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. Get property value from C# dynamic object by string (reflection?)
  2. How to access property of anonymous type in C#?//只有事先知道属性名称才能访问属性。

非常感谢任何帮助!

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com