C# 使用具有反射的值加载对象

C# 使用具有反射的值加载对象,c#,reflection,C#,Reflection,使用下面的代码,我试图在xml文档中保存和加载一个播放器类。我的写入部分工作正常,但我在使用playerElement中存储的数据重新填充player对象时遇到了一些问题。我不希望使用xml序列化程序类 public class Player { public string Name { get; set; } public int HitPoint { get; set; } public int ManaPoint { get; se

使用下面的代码,我试图在xml文档中保存和加载一个播放器类。我的写入部分工作正常,但我在使用playerElement中存储的数据重新填充player对象时遇到了一些问题。我不希望使用xml序列化程序类

    public class Player
    {
       public string Name { get; set; }
       public int HitPoint { get; set; }
       public int ManaPoint { get; set; }
    }


    public Player LoadPlayer(XElement playerElement)
    {

        Player player = new Player();

        PropertyInfo[] properties = typeof(Player).GetProperties();

        foreach (XAttribute attribute in playerElement.Attributes())
        {
            PropertyInfo property = typeof(Player).GetProperty(attribute.Name.ToString());


            if (property != null)
            {


                object dataValue = Convert.ChangeType(attribute.Value, property.PropertyType);



                 property.SetValue(player, dataValue);

            }
        }

        return player;
    }


   public override void Write(Player value)
   {

        PropertyInfo[] properties = typeof(Player).GetProperties();

        XElement playerElement = new XElement(XmlChildName);

        foreach (PropertyInfo property in properties)
        {
            playerElement.Add(new XAttribute(property.Name, property.GetValue(value,   null).ToString()));
        }

        _doc.Root.Add(playerElement);

        _doc.Save(Path);
    }

我想你需要这样的东西。我将遍历反转为属性,而不是属性。如果存在具有属性名称的属性,则会对其进行更改:

PropertyInfo[] properties = typeof(Player).GetProperties();

foreach (XAttribute attribute in playerElement.Attributes())
{
    PropertyInfo pi = properties.Where(x => x.Name == attribute.Name).FirstOrDefault();

    if (pi != null)
    {
        pi.SetValue(player, attribute.Value);
    }
}

对xml序列化程序类有什么保留?我同意xml序列化程序可能非常适合您。就我个人而言,我担心玩家类在某一点上需要您不希望序列化的属性。然后,您可以考虑卸载SAVER()和Load()到播放器类。@帕特里克:是的,我不清楚,我的意思是使用反射的实现可能是毛茸茸的,而不是使用XML序列化器的实现。谢谢您的指导,我最终使用了这个解决方案,它看起来很好。我会更新代码