使用带反射的值加载对象

时间:2014-05-16 13:30:32

标签: c# reflection

使用下面的代码,我试图在xml文档中保存并加载播放器类。我有写部分工作但我在使用存储在playerElement中的数据重新填充播放器对象时遇到了一些麻烦。我宁愿不使用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);
    }

1 个答案:

答案 0 :(得分:1)

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

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