3 c# generics properties dynamic anonymous-types
我知道这个主题在stackoverflow上有很多问题,但我找不到任何具体的答案来解决我目前的情况.
Run Code Online (Sandbox Code Playgroud)// 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 */ }
Run Code Online (Sandbox Code Playgroud)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,但解决方案仅在您知道属性名称时才会出现
任何帮助是极大的赞赏!
获取第一个项目,将其强制转换为对象,然后您可以获取属性:
object e = collection.FirstOrDefault();
var columns = e.GetType().GetProperties().Length;
Run Code Online (Sandbox Code Playgroud)
要不就:
collection.FirstOrDefault().GetType().GetProperties().Length;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8396 次 |
| 最近记录: |