在 forloop 内部和外部创建对象是否有区别..我不确定,但我遇到了一个错误,因为在 forloop 外部声明了 oCategoryDefinition:
在 System.Int32.System.IConvertible.ToType(类型类型,IFormatProvider 提供程序)的 System.Convert.DefaultToType(IConvertible 值,类型 targetType,IFormatProvider 提供程序)从“System.Int32”到“xxx.CategoryDefinition”的无效转换。在 Service.AddFeatureValues(VINDescription vinDescription, VehicleDescription vehicleDescription) 处的 Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
>
for (int i = 0; i < listLength; i++)
{
CategoryDefinition oCategoryDefinition = (CategoryDefinition)Convert.ChangeType
(vehicleDescription.genericEquipment[i].Item, typeof(CategoryDefinition));
vinDescription.StandardFeature.Add(oCategoryDefinition.category.Value);
}
和
CategoryDefinition oCategoryDefinition = new CategoryDefinition();
for (int i = 0; i < listLength; i++)
{
oCategoryDefinition = (CategoryDefinition)Convert.ChangeType
(vehicleDescription.genericEquipment[i].Item, typeof(CategoryDefinition));
vinDescription.StandardFeature.Add(oCategoryDefinition.category.Value);
}
编辑
为问题添加一个角度:以下是引发上述错误的方法:
private void AddFeatureValues(VINDescription vinDescription, VehicleDescription vehicleDescription)
{
GenericEquipment[] genericEquipList = null;
//To add standard features to the vehicle details list.
CategoryDefinition oCategoryDefinition = new CategoryDefinition();
try
{
genericEquipList = vehicleDescription.genericEquipment;
if (genericEquipList != null)
{
//Stores the number of items in generic list.
int listLength = genericEquipList.Length;
for (int i = 0; i < listLength; i++)
{
//Casting the object type to CategoryDefinition type.
oCategoryDefinition = (CategoryDefinition)Convert.ChangeType(vehicleDescription.genericEquipment[i].Item,
typeof(CategoryDefinition));
vinDescription.StandardFeature.Add(oCategoryDefinition.category.Value ?? "N/A");
}
}
}
catch (Exception ex)
{
}
}