从Dictionary中向Object添加属性值

时间:2014-11-17 07:00:21

标签: c# asp.net .net reflection .net-reflector

所以我有一个名为PaypalTransaction的对象,这里是它的开头,不需要显示所有属性来解释问题。

public class PaypalTransaction
{
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string custom { get; set; }
    public string payer_email { get; set; }
    ....
    ....
}

现在我的问题是,我有一个foreach循环,每个键都是一个字符串

PaypalTransaction trans = new PaypalTransaction();
foreach(string key in keys)
{
    // key = "first_name" ,  or "last_name , or "custom"
    // how would I set the value of trans based on each key
    //  so when key = "first_name , I want to set trans.first_name
    // something like trans.PropName[key].Value = 
    // I know that code isn't real , but with reflection i know this is possible

 }

1 个答案:

答案 0 :(得分:1)

您可以从trans对象获取属性集合并在循环之前对其进行缓存。您可以遍历它并设置适当属性的值。以下示例可能有所帮助:

PaypalTransaction trans = new PaypalTransaction();

            PropertyInfo[] properties = trans.GetType().GetProperties();

            foreach (string key in keys)
            {
                properties.Where(x => x.Name == key).First().SetValue(trans, "SetValueHere");

            }

您可能需要针对性能和其他可能的异常优化上述代码。