c# - 将 IEnumerable<T> 转换为对象 [,] C#

标签 c# generics reflection

我正在尝试构建一个将任何 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/

相关文章:

java - 为什么在映射到 Callable<T> 时需要显式提供类型参数?

java - Java 中的泛型类型推断限制

java - 为什么原始类型不能具有具有泛型返回类型的方法

c# - 如何通过反射获取属性的 DisplayAttribute?

java - 小程序中使用GSON库时的反射权限问题

c# - 使用 propertyBuilder 在运行时向现有对象添加属性

c# - 在c#中添加数字

c# - File.WriteAllText 不保留换行符

c# - 在 ASP.NET 中的两点之间绘制箭头

c# - 如何以编程方式读取 packages.config 中的 NuGet 包列表?