所以我有一个名为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");
}
您可能需要针对性能和其他可能的例外情况优化上面的代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句