在for循环中创建对象

时间:2012-09-28 10:29:29

标签: c# c#-4.0

在循环内部和外部创建对象有什么不同。我不确定但是我遇到了在forloop之外声明oCategoryDe​​finition的错误:

  

从'System.Int32'到'xxx.CategoryDe​​finition'的无效演员表        在System.Convert.DefaultToType(IConvertible值,类型targetType,IFormatProvider提供程序)        在System.Int32.System.IConvertible.ToType(Type type,IFormatProvider provider)处于System.Convert.ChangeType(Object value,Type conversionType,IFormatProvider provider)at at       Service.AddFeatureValues(VINDescription vinDescription,VehicleDescription vehicleDescription)

>

  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)
        {  
        }
    }

2 个答案:

答案 0 :(得分:1)

或许尝试以下方法,因为唯一的主要区别是新关键字。

CategoryDefinition oCategoryDefinition;

for (int i = 0; i < listLength; i++)
{
   oCategoryDefinition = (CategoryDefinition)Convert.ChangeType
       (vehicleDescription.genericEquipment[i].Item, typeof(CategoryDefinition));
   vinDescription.StandardFeature.Add(oCategoryDefinition.category.Value);
}

然而,演员表的异常并没有真正帮助我。

答案 1 :(得分:0)

在第二种情况下,由于扩展的变量范围(例如方法),你仍然可以引用在最后一次迭代后持续的对象,因此使用第一个版本更安全。

但是(取决于框架如何实现创建引用)可能会对性能产生轻微影响,这在迭代次数变大时非常重要。