繁体   English   中英

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

[英]InvalidCastException: Cannot cast from source type to destination type. (Unity c# ,foreach list loop)

嗨,我有这个代码的问题。

它抛出一个

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;
}

如果您确定在每一个项目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的元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM