4

looking for hours now on this particular question, I hope you can help. Following class hierachy is given:

public class Toon 
{
 public Skillset skillset;

 public Toon()
 {

    skillset = new Skillset();
 }
}

public class Skillset 
{
    public Skill Fight;
    public Skill Trade;
    public Skill Talk;


   public Skillset()
   {
        Fight = new Skill() { name = "Fight", value = 10 };
        Trade = new Skill() { name = "Trade", value = 12 };
        Talk = new Skill() { name = "Talk", value = 15 };
   }

}

public class Skill
{ 
    public string Name;
    public int Value;
    public int Rank

} 

This is to provide the Syntax of Toon.Skillset.Fight etc.

Now the question: I want to be able to randomly increase Skills, if they are in the favorites list, which is a List.

So basicly:

public void setSkill(string skillname, Toon toon, int value)
{
  => get property and set it to value
}

so that

setSkill("Fight", NewToon, 30); would set Toon.Skillset.Fight to 30.

I hope I could explain clear enough, and I'm thankful for any input. I heard of Reflection to solve this problem nicely, but I found no answer yet.

PS: just getting a List in Toon wouldn't help, it destroys the syntax.

Ceron
  • 43
  • 5
  • 4
    BTW, you have Fields in your classes, not Properties. – LarsTech Aug 26 '16 at 15:08
  • 1
    You could just use an indexer. public Skill this[string name] { get { switch (name) { case "Fight": return Fight; case "Trade": return Trade; case "Talk": return Talk; default: return null; } } } – J. Allen Aug 26 '16 at 15:30
  • true, still the final model will have around 30 fields, so tha would not feel right to me. Whith the few fields provided, you're right of course. – Ceron Aug 28 '16 at 12:44
  • @LarsTech: Ah, yes, thanks :) – Ceron Aug 28 '16 at 12:45

1 Answers1

1

You could use reflection:

public void setSkill(string skillname, Toon toon, int value)
{
    var field = typeof(Skillset).GetField(skillname);
    var skill = (Skill)field.GetValue(toon.skillset);

    skill.Value = value;
}

But, this isn't the most performing solution. You should consider using a Dictionary<string, Skill> as your Skillset.

Xiaoy312
  • 14,292
  • 1
  • 32
  • 44