C# 将常规列表或字符串[]数组转换为datatable时出现问题

C# 将常规列表或字符串[]数组转换为datatable时出现问题,c#,C#,我有下面的功能 public static DataTable ToTable<T>(this IEnumerable<T> listItem) { //Return null if the list is empty if (listItem == null || listItem.Count() == 0) return null; //Gets the type of the object

我有下面的功能

public static DataTable ToTable<T>(this IEnumerable<T> listItem)
{
            //Return null if the list is empty
            if (listItem == null || listItem.Count() == 0) return null;

            //Gets the type of the object
            var listType = listItem.First().GetType();

            //Initialize a new datatable
            var dataTable = new DataTable(listType.Name);
            //Create the datatable column names and types
            listType.GetProperties().ToList().ForEach(col => dataTable.Columns.Add(col.Name, col.PropertyType));

            //Get the datatable column names
            var dataTableColumnNames = dataTable.GetDatatableColumnNames();

            listItem.ToList().ForEach(item =>
            {
                //create a new datarow
                var dataRow = dataTable.NewRow();

                dataTableColumnNames
                .Where(propName => listType.GetProperty(propName) != null)
                .ToList()
                .ForEach(columnName => 

//Exception happens here in the next line
     dataRow[columnName] = listType.GetProperty(columnName).GetValue(item, null));     
                //Add the row to the data table
                dataTable.Rows.Add(dataRow);
            });

            //Commit the changes to the datatable
            dataTable.AcceptChanges();
            return dataTable;
        }
正在发生的错误是什么


请提供帮助

,因为字符串的公共属性之一是索引器,您将null作为索引值传递。因此,您实际上最终会这样做:字符串[null],它最终会出现异常

我还没有验证这一点,因为我现在没有可用的VS,所以我可能错了,但我很确定这就是问题所在


更新:此问题回答了如何检测索引属性:

交易如下。在使用反射时,索引运算符实际上被视为一个属性,因此参数计数不匹配

如果您打断代码并检查GetProperties实际枚举的属性,您将看到Chars属性。这是字符串的索引运算符。由于没有提供索引,因此会出现参数计数不匹配错误

本质上,我假设string没有任何要放在数据表中的属性,但是string实例是要放在数据表中的

您可以创建一个模型来存储字符串,将字符串作为模型上的属性,然后字符串将与当前代码一起存储。否则,您将需要重新考虑基本类型的表生成算法


我希望这有帮助:

我们需要猜测异常抛出的位置吗?您能更准确地指出代码中异常抛出的位置吗?我已经更新了这一点。。它在dataRow[columnName]=listType.GetPropertycolumnName.GetValueitem处出现,null;e、 字符串[]strNames={Name1,Name2,Name3,Name4,Name5,Name6};strNames.ToTable;抛出异常
dataRow[columnName] = listType.GetProperty(columnName).GetValue(item, null));