【问题标题】:Add Property values to Object from Dictionary将属性值添加到字典中的对象
【发布时间】:2014-11-17 07:00:20
【问题描述】:

所以我有一个名为 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

 }

【问题讨论】:

  • 使用反射或简单地使用Dictionary<string,Object>

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


【解决方案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");

            }

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

【讨论】:

  • 现在不关心性能,当我需要开始关心的时候,因为购买的速度如此之快,以至于陷入困境 - 我的事情进展顺利
  • 我实际上正在研究一个看起来非常接近这个的答案,但是没有 lambda ,我不确定如何使用 .SetValue ,谢谢,这应该可以工作,当它让我接受时我会接受
猜你喜欢
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-03
  • 2017-02-09
  • 2015-11-15
相关资源
最近更新 更多