Reputation: 119
I just started programming and I dont even know if this is even possible...
I have the following Interface:
public interface ISkills
{
int SelfHeal();
int AditionDamage();
int DoubleDamage();
int DefenseMatrix();
}
and the following base 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;
}
}
}
In main the user gets asked to choose 2 skills. How can I add the chosen methods to my list (because the add() doesnt work...) and how can I call the methods in the list then?
Upvotes: 0
Views: 150
Reputation: 336
Here:
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;
}
}
}
In which by typing skills["DefenseMatrix"]()
(or instead of "DefenseMatrix"
any other key "key"
you defined in skills.Add("key", theFunc);
) you execute the method.
If there is no matching "key"
found this will raise an error.
You can check if a key exists by if (skills.ContainsKey("key"))
If you actually just wanted to determine which methods the character is allowed to do and which not, you might benefit from looking into [Flags] enum
's. It seems [Flags]
would be a better way.
Upvotes: 1