[英]Add Property values to Object from Dictionary
所以我有一个叫做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
}
您可以从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");
}
您可能需要针对性能和其他可能的例外情况优化上面的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.