如何获得未知属性的值(部分已经用反射解决)

本文关键字:反射 解决 未知 何获得 属性 | 更新日期: 2023-09-27 17:53:12

我有一个现有的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;
    }

非常感谢您的帮助。

如何获得未知属性的值(部分已经用反射解决)

try this

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

您要查找的是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


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

您可以这样做。(顺便说一下,您的代码可能会在"字典键不唯一"上出错,因为第二个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);
}