将接口字典迭代为特定类型

时间:2019-06-25 13:02:54

标签: c# unity3d

我有一个字符串/接口类字典。我不能在接口子类中包括我需要的字段,但是每个字段都有我需要更改的相同公共变量。

我想遍历字典并将其更改为循环类中的值。我不能这样做,因为接口不包含那些变量。

我应该怎么做?

public class MakeAbility : MonoBehaviour
{
public BlockScriptableObject block;

public IDictionary<string, IAbility> abilities_parts = new Dictionary<string, IAbility>();


public Targeting target_manager;

public AbAttack attack;
public AbCast cast;
public AbDefend defend;
public AbDefendOther defend_other;
public AbPotion potion;

private void Start()
{
    abilities_parts.Add("attack", attack);
    abilities_parts.Add("cast", cast);
    abilities_parts.Add("defend", defend);
    abilities_parts.Add("defend_other", defend_other);
    abilities_parts.Add("potion", potion);
}

public void trigger_button()
{
    foreach (var i in abilities_parts.Values)
    {
        i.block_attack_damage = block.attack_damage;
        i.targeting_for_attack = target_manager;
    }



public interface IAbility
{
void Use();
void Enact();
}

public class AbPotion : MonoBehaviour, IAbility
{
public Targeting targeting_for_attack;
public int block_attack_damage = 10;

public void Use()
{

}

public void Enact()
{

}

}

1 个答案:

答案 0 :(得分:0)

您的属性不是IAbility的属性。它们是AbPotion类的属性。您需要在类型上使用if else语句来分别设置它们。事实是,应该在将它们添加到Dictionary之前,可能已经通过构造函数进行了设置。

public void trigger_button()
{
    foreach (var i in abilities_parts.Values)
    {
        if(i is AbPotion)
        {
            var potion = i as AbPotion;

            potion.block_attack_damage = block.attack_damage;
            potion.targeting_for_attack = target_manager;
        }
        else if(i is AbAttack)
        {
            var attack = i as AbAttack;

            attack.Property1= value1;
            attack.Property2 = value2;
        }
    }
}