【问题标题】:How to get value of unknown properties (part solved already with reflection)如何获取未知属性的值(部分已通过反射解决)
【发布时间】:2015-06-03 17:01:37
【问题描述】:

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

非常感谢您的帮助。

【问题讨论】:

    标签: c# reflection properties


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 任何其他细节/解释都会有所帮助。
    【解决方案2】:

    您正在寻找的是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
    指定对象的属性值。

    【讨论】:

    • 添加更多关于property.GetValue的细节,你需要传递userItem作为第一个参数来告诉编译器需要从哪个引用变量数据中查找。
    【解决方案3】:

    这就是你可以做到的。 (顺便说一句,您的代码可能会在“字典键不唯一”上出错,因为第二个 userItem 会尝试将相同的属性名称添加到字典中。您可能需要 List&lt;KeyValuePair&lt;string, string&gt;&gt;

            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 并使用以下 sn-p。

    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);
    }
    

    【讨论】:

    • @B.K. property.GetValue 将返回一个对象。我们不能直接将它添加到字典中,因为需要一个字符串值。因此进行空检查。请看字典定义。它需要一个字符串值。如果我遗漏了什么,请告诉我。很高兴纠正自己。
    • 谢谢你的工作,你对字典的看法是对的。我将使用该列表。
    • 酷。如果您使用列表,您可能不知道哪个属性对应于哪个 userItem。例如如果有 2 个 userItem,那么您会说两个“名称”属性,不知道它属于 userItem 1 还是 2。解决方法是像您原来的想法一样使用 Dictionary,但是当您添加密钥时,将其添加为 (property.Name + "[" + index + "]") 以便获得用户项的索引。这将为您提供一个字典,其中所有 [0] 键都属于 userItem1 等等。
    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多