簡體   English   中英

C# 我可以將接口方法添加到列表中嗎?

[英]C# Can I add Interface methods to a list?

我剛開始編程,我什至不知道這是否可能......

我有以下界面:

public interface ISkills
{
    int SelfHeal();
    int AditionDamage();
    int DoubleDamage();
    int DefenseMatrix();
}

和以下基地 class:

class NetNavi : ISkills
{
    List<ISkills> skills = new List<ISkills>();
     
    int ISkills.SelfHeal()
    {
        return 5;
    }

    int ISkills.AditionDamage()
    {
        return 5;
    }

    int ISkills.DoubleDamage()
    {
        return 5;
    }

    int ISkills.DefenseMatrix()
    {
        return 5;
    }
     
    
    public void AddSkills(int chosenSkill)
    {
        switch(chosenSkill)
        {
            case 1:
                //add SelfHeal to the list
                break;
            case 2:
                //add AditionDamage to the list
                break;
            case 3:
                //add DoubleDamage to the list
                break;
            case 4:
                //add DefenseMatrix to the list
                break;
        }
    }
}

主要是要求用戶選擇 2 項技能。 我怎樣才能將選擇的方法添加到我的列表中(因為 add() 不起作用......)然后我怎樣才能調用列表中的方法?

這里:

class NetNavi : ISkills
    {
        Dictionary<string, Func<int>> skills = new Dictionary<string, Func<int>>();
     
        int SelfHeal()
        {
            return 5;
        }

        int AditionDamage()
        {
            return 5;
        }

        int DoubleDamage()
        {
            return 5;
        }

        int DefenseMatrix()
        {
            return 5;
        }
     
    
            
       

 public void AddSkills(int chosenSkill)
        {
            switch(chosenSkill)
            {
                case 1:
                    Func<int> theFunc = SelfHeal;
                    skills.Add("SelfHeal", theFunc);
                    break;
                case 2:
                    Func<int> theFunc = AditionDamage;
                    skills.Add("AditionDamage", theFunc);
                    break;
                case 3:
                    Func<int> theFunc = DoubleDamage;
                    skills.Add("DoubleDamage", theFunc);
                    break;
                case 4:
                    Func<int> theFunc = DefenseMatrix;
                    skills.Add("DefenseMatrix", theFunc );
                    break;
            }   
        }
}

在其中通過鍵入skills["DefenseMatrix"]() (或者代替"DefenseMatrix" ,您在skills.Add("key", theFunc);中定義的任何其他鍵"key" )執行該方法。

如果沒有找到匹配的"key" ,這將引發錯誤。

您可以通過if (skills.ContainsKey("key"))檢查密鑰是否存在

如果您實際上只是想確定角色可以使用哪些方法,哪些方法不能使用,那么查看[Flags] enum可能會有所幫助。 看來[Flags]會是更好的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM