【问题标题】:error "Unable to cast object of type 'System.Int32' to type 'System.Collections.Generic.List`1[System.Int32]'"错误“无法将'System.Int32'类型的对象转换为'System.Collections.Generic.List`1 [System.Int32]'”
【发布时间】:2013-10-06 21:47:02
【问题描述】:

我有一个包裹递送应用程序,但在下面的代码中出现错误:

public class DeliveryDriver
{
    public List<int> DriverID { get; set; }
    public List<string> DriverName { get; set; }
}

var IDeliveryDriver = new List<DeliveryDriver>();

foreach (DataRow dr in dsDriverID.Tables[0].Rows)
{
    IDeliveryDriver.Add(new DeliveryDriver
    {
        DriverID = (List<int>)dr["DriverId"],
        DriverName = (List<string>)dr["DriverName"]
    });
}

错误发生在IDeliveryDriver.Add 行,它进入一个catch 块。错误是:

无法将“System.Int32”类型的对象转换为类型 'System.Collections.Generic.List`1[System.Int32]'

是什么导致了错误?

【问题讨论】:

  • 5 不是一个列表。这是一个 5。
  • DeliveryDriver 的 DriverID 真的应该是 List&lt;int&gt; 吗?就像错误所说的那样,您不能将 dr["DriverId"] 转换为 List&lt;int&gt;。

标签: c# asp.net generics collections


【解决方案1】:

错误消息说明了一切 - 每行中的 DriverId 字段是 int,而不是 List&lt;int&gt;。 DriverName 也是 string,而不是 List&lt;string&gt;。您应该将DriverId 和DriverName 属性分别更改为int 和string,然后也转换为正确的类型:

public class DeliveryDriver
{
    public int DriverID { get; set; }
    public string DriverName { get; set; }
}

...

foreach (DataRow dr in dsDriverID.Tables[0].Rows)
{
    IDeliveryDriver.Add(new DeliveryDriver
    {
        DriverID = (int) dr["DriverId"],
        DriverName = (string) dr["DriverName"]
    });
}

毕竟,每个送货司机只有一个名字和一个身份证,不是吗?

【讨论】:

    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多