简体   繁体   English

向字典中的对象添加属性值

[英]Add Property values to Object from Dictionary

So I have an Object called PaypalTransaction here is the begining of it , don't need to show all properties to explain question. 所以我有一个叫做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; }
    ....
    ....
}

now my questions is , I have a foreach loop that has each key as a string 现在我的问题是,我有一个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

 }

You can get the collection of properties from trans object and cache it before the loop. 您可以从trans对象获取属性集合,并在循环之前将其缓存。 The you can loop through that and set the values of appropriate properties. 您可以循环浏览并设置适当属性的值。 Following sample may help: 以下示例可能会有所帮助:

PaypalTransaction trans = new PaypalTransaction();

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

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

            }

You may need to optimize the code above for performance and other possible exceptions. 您可能需要针对性能和其他可能的例外情况优化上面的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM