【问题标题】:Using reflection to set properties from a dictionary使用反射从字典中设置属性
【发布时间】:2013-09-23 06:21:09
【问题描述】:

我有一个带有一些属性的对象和一个为每个属性保存一个临时值的字典。这个字典的键是一个与属性同名的字符串,而值是一个对象。

我要做的是构建一个读取字典键并将相应属性设置为字典中找到的值的保存方法。

所以我想到了反思,但这并不像我想象的那么容易。

这是一个示例类:

public class Class{
    public string Property1 { get; set; }
    public int Property2 { get; set; }
    public Dictionary<string, object> Settings { get; set; }

    public void Save()
    {
        foreach (string key in Settings.Keys)
        {
            // PSEUDOCODE
            get the property called like the key
            get its type
            get the value of hte key in the dictionary
            cast this object to the property's value
            set the property to the casted object
        }
    }
}

我不发布代码的原因是因为我不明白如何进行强制转换和类似的事情,所以我写了一点伪代码让你了解我想要实现的目标。

有没有人可以指出正确的方向?

【问题讨论】:

  • 为什么不将值保留在字典中。只需实现您的属性,例如public string Property1 { get { return (string)Settings["Property1"]; } set { Settings["Property1"] = value; }}
  • 属性用于绑定,字典用于给用户编辑和撤销的机会。因此,只有当用户确认时,字典才会覆盖属性,否则属性不会更改,它们会保留旧值。可能这不是最好的方法,但在我看来这很容易。
  • 听起来你应该实现深拷贝/克隆并让用户编辑副本。

标签: c# reflection properties casting windows-phone-8


【解决方案1】:

这里:

//Get the type
var type= this.GetType();

foreach (string key in Settings.Keys) 
{
    //Get the property
    var property = type.GetProperty(key);
    //Convert the value to the property type
    var convertedValue = Convert.ChangeType(Settings[key], property.PropertyType);
    property.SetValue(this, convertedValue); 
}

未经测试,但应该可以。

【讨论】:

  • 它可以工作,但ChangeType 方法先获取对象,然后再获取其类型。
  • 您甚至不需要先更改类型,因为 SetValue() 无论如何都需要 Object。只需property.SetValue(this, Settings[key], null);
猜你喜欢
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
  • 2021-02-21
相关资源
最近更新 更多