我正在尝试构建一个将任何 IEnumerable 转换为对象 [,] 的通用方法。这样做的目的是通过 ExcelDNA 插入到 excel 中,理想情况下需要二维对象数组。
我是反射(reflection)的新手,需要一些认真的帮助来填补这里的空白。 下面发布的代码是我目前所拥有的,我需要的是在外循环中的数据源的索引 i 处获取 T 的属性。然后在内循环中依次获取每个属性的值并插入到对象[,]中。
感谢任何帮助。 谢谢 理查德
public object[,] ConvertListToObject<T>(IEnumerable<T> DataSource)
{
int rows = DataSource.Count();
//Get array of properties of the type T
PropertyInfo[] propertyInfos;
propertyInfos = typeof(T).GetProperties(BindingFlags.Public);
int cols = propertyInfos.Count(); //Cols for array is the number of public properties
//Create object array with rows/cols
object[,] excelarray = new object[rows, cols];
for (int i = 0; i < rows; i++) //Outer loop
{
for(int j = 0; j < cols; j++) //Inner loop
{
object[i,j] = //Need to insert each property val into j index
}
}
return excelarray;
}
}
最佳答案
你很接近。一些提示:
- 外部循环需要是一个
foreach
循环,因为您通常无法通过索引有效地访问IEnumerable
。 -
GetProperties
需要BindingFlags.Static
或.Instance
才能返回任何内容。 - 您可以通过调用
propertyInfos[j].GetValue
获得实际值,传入你想从中获取它的T
实例和一个索引器值数组 - 对于常规属性为 null,但如果你的对象可能具有索引属性,你要么需要找出一些东西来在此处传递或处理可能抛出的异常。
我得到这样的东西:
public object[,] ConvertListToObject<T>(IEnumerable<T> DataSource)
{
int rows = DataSource.Count();
//Get array of properties of the type T
PropertyInfo[] propertyInfos;
propertyInfos = typeof(T).GetProperties(
BindingFlags.Public |
BindingFlags.Instance); // or .Static
int cols = propertyInfos.Length;
//Create object array with rows/cols
object[,] excelarray = new object[rows, cols];
int i = 0;
foreach (T data in DataSource) //Outer loop
{
for (int j = 0; j < cols; j++) //Inner loop
{
excelarray[i, j] = propertyInfos[j].GetValue(data, null);
}
i++;
}
return excelarray;
}
关于c# - 将 IEnumerable<T> 转换为对象 [,] C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12706680/