[英]error “Unable to cast object of type 'System.Int32' to type 'System.Collections.Generic.List`1[System.Int32]'”
I have an package delivery application and I am getting an error in my code below: 我有一个包交付应用程序,我在下面的代码中收到错误:
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"]
});
}
The error occurs at the IDeliveryDriver.Add
line and it goes into a catch block. 错误发生在
IDeliveryDriver.Add
行,它进入catch块。 The error is: 错误是:
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]'
What is causing the error? 是什么导致错误?
The error message says it all - the DriverId
field in each row is an int
, not a List<int>
. 错误消息说明了一切 - 每行中的
DriverId
字段是一个int
,而不是List<int>
。 Ditto for DriverName
being a string
, not a List<string>
. 同样,
DriverName
是一个string
,而不是List<string>
。 You should change your DriverId
and DriverName
properties to be int
and string
respectively, then cast to the right type too: 您应该将
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"]
});
}
After all, each delivery driver does only have one name and one ID, don't they? 毕竟,每个送货司机只有一个名字和一个身份证,不是吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.