【问题标题】:C# Parameter count mismatch converting List to DataTableC# 参数计数不匹配将 List 转换为 DataTable
【发布时间】:2017-10-21 04:48:06
【问题描述】:

我得到了代码行标题中提到的异常

values[i] = Props[i].GetValue(item, null); 

我不确定是什么原因造成的。任何帮助,将不胜感激。

public static DataTable ToDataTable<T>(List<T> items)
{
    DataTable dataTable = new DataTable(typeof(T).Name);


    PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (PropertyInfo prop in Props)
    {

        var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);

        dataTable.Columns.Add(prop.Name, type);
    }
    foreach (T item in items)
    {
        var values = new object[Props.Length];
        for (int i = 0; i < Props.Length; i++)
        {
            values[i] = Props[i].GetValue(item, null);
        }
        dataTable.Rows.Add(values);
    }

    return dataTable;
}

【问题讨论】:

  • 你传入的是什么类型的数据?该方法似乎适用于我的测试。例如,这里有一个基本集合:dotnetfiddle.net/6RWBpz
  • 为您找到了一篇相关文章,通过快速谷歌搜索您的主题行:stackoverflow.com/questions/32143085/…
  • 数据是一个字符串列表。
  • 动态类型只能是等于 T 的 1 个值。我认为您从 Props 将 dataTable 列循环和设置为多种类型是不正确的。但这是一个猜测。

标签: c# list datatable


【解决方案1】:

如果这行抛出异常

values[i] = Props[i].GetValue(item, null); 

...那么这意味着您有一个需要参数的属性。在 c# 中,唯一带参数的属性类型是 indexer。我的猜测是你应该从循环中排除索引器。

请参阅this question,它告诉您如何检测索引器。

您可以通过更改一行来解决此问题。改变这个...

PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

...到这个....

PropertyInfo[] Props = typeof(T)
    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
    .Where(p => p.GetIndexParameters == null))
    .ToArray();

【讨论】:

    【解决方案2】:

    问题实际上在于我传递给方法的数据(字符串列表)。 GetValue() 方法似乎正在寻找一个对象。我创建了一个带有字符串属性的类,并更改了传递给类的列表类型,并将类中的属性设置为我在 foreach 循环中传递给列表的字符串。抱歉,如果只是试图解释我是如何解决这个问题的,这没有意义,但问题可能已经通过多种方式解决。谢谢大家。

    【讨论】:

      猜你喜欢
      • 2013-10-14
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多