This question already has answers here:
Get property value from string using reflection in C#
                                
                                    (22个答案)
                                
                        
                                3年前关闭。
            
                    
现在就这个特定问题找几个小时,希望您能提供帮助。
给出以下类层次结构:

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

}


这是为了提供Toon.Skillset.Fight等语法。

现在的问题是:
我希望能够随机增加“技能”,如果它们在“收藏夹”列表(即列表)中。

所以基本上:

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


以便

setSkill(“ Fight”,NewToon,30);将Toon.Skillset.Fight设置为30。

我希望我能解释得足够清楚,感谢您的投入。我听说Reflection可以很好地解决此问题,但尚未找到答案。

PS:仅在Toon中获得列表将无济于事,它破坏了语法。

最佳答案

您可以使用反射:

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


但是,这不是性能最高的解决方案。您应该考虑使用Dictionary<string, Skill>作为Skillset

10-04 15:17