如何获取未知属性的值(部分已通过反射解决)

How to get value of unknown properties (part solved already with reflection)

我有一个现有的 c# 应用程序需要修改,需要循环遍历一个属性未知的对象,并且已经通过反射解决了一半问题。

我正在尝试用 属性 名称和 属性 值填充字典。代码在下面,我已经在 ***s

之间描述了我需要什么

这是一个 MVC5 项目

    private Dictionary<string, string> StoreUserDetails ()
    {      
      var userDetails = new Dictionary<string, string>();

      foreach (var userItem in UserItems)
      {
        var theType = userItem.GetType();
        var theProperties = theType.GetProperties();

        foreach (var property in theProperties)
        {
          userDetails.Add(property.Name, ***value of userItem property with this property name***);
        }
      }      
      return userDetails;
    }

非常感谢您的帮助。

您要查找的是 PropertyInfo.GetValue() 方法:
https://msdn.microsoft.com/en-us/library/b05d59ty%28v=vs.110%29.aspx

例子

property.GetValue(userItem, null);

语法

public virtual Object GetValue(
    Object obj,
    Object[] index
)

参数

obj
输入:System.Object
将返回其 属性 值的对象。

index
输入:System.Object[]
索引属性的可选索引值。索引属性的索引是从零开始的。对于非索引属性,此值应为 null

Return值

类型:System.Object
指定对象的 属性 值。

您可以这样做。 (顺便说一句,您的代码可能会在 "dictionary key not being unique" 上出错,因为第二个 userItem 会尝试将相同的 属性 名称添加到字典中。您可能需要 List<KeyValuePair<string, string>>

        foreach (var property in theProperties)
        {
            // gets the value of the property for the instance.
            // be careful of null values.
            var value = property.GetValue(userItem);

            userDetails.Add(property.Name, value == null ? null : value.ToString());
        }

顺便说一下,如果您处于 MVC 上下文中,则可以参考 System.Web.Routing 并使用以下代码段。

foreach (var userItem in UserItems)
{
 // RVD is provided by routing framework and it gives a dictionary 
 // of the object property names and values, without us doing 
 // anything funky. 
 var userItemDictionary= new RouteValueDictionary(userItem);
}

试试这个

foreach (var property in theProperties)
{
  var userItemVal = property.GetValue(userItem, null);
  userDetails.Add(property.Name, userItemVal.ToString());
}