InvalidCastException:无法从源类型转换为目标类型。 (Unity C#,foreach列表循环)

时间:2018-07-21 23:50:04

标签: c# list unity3d foreach

嗨,我的代码有问题。

它抛出一个

  

InvalidCastException:无法从源类型转换为目标类型。

当尝试访问清单中的WeaponClass对象时:

public static List<ItemsClass> EquiptWeapon(EquipablesClass o, List<ItemsClass> inventory)

{//This function recive a item class (o) and a List


    if (o is WeaponsClass)
    {
        //This line here is the problematic one (InvalidCastException: Cannot cast from source type to destination type.)
        foreach (WeaponsClass z in inventory) {
           //This loop is made so if i already have a weapons equipped this will unequipped
           z.IsEquipted = false;
        }

       //Then i equip the weapon that was passed
        o.IsEquipted = true;

       //The player class has a weapon class in it, so now i assign it. So i can ask directly to the player class when i need the info
        WeaponsClass y = o as WeaponsClass;

        Player.player.WeaponEquip = y;

    }
    return inventory;
}

1 个答案:

答案 0 :(得分:2)

如果您确定List<ItemsClass> inventory中的每一项都是WeaponsClass类型,则可以执行以下操作:

foreach (var item in inventory.Cast<WeaponsClass>())
{
    //...
}

请注意,即使有一项无法转换为WeaponClass,也将引发异常。您可以采用的另一种方法是:

foreach (var item in inventory)
{
    var casted = item as WeaponClass; // No exception if cast fails, simply returns null
    if(casted != null)
    {
        //...
    }
}

您可以采用的另一种方法是:

foreach (var item in inventory.OfType<WeaponsClass>())
{
    //...
}

及其文档非常清楚:

  

根据指定的类型过滤System.Collections.IEnumerable的元素。