[英]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.