【问题标题】:Get second level property value using reflection使用反射获取二级属性值
【发布时间】:2014-06-11 05:54:26
【问题描述】:

我写了一个扩展方法来获取对象的属性值。这就是代码:

public static string GetValueFromProperty(this object obj, string Name)
{
    var prop = obj.GetType().GetProperty(Name);
    var propValue = prop != null ? (string)prop.GetValue(obj, null) : string.Empty;
    return propValue;
}

它适用于一级属性。现在我有一个问题。我想获取下拉列表的选定文本,我这样称呼它:

string s = drp.GetValueFromProperty("SelectedItem.Text");

但它不会返回任何东西。

如何扩展从二级属性(或一般形式的任何级别)返回值的扩展方法?

谢谢

【问题讨论】:

    标签: c# c#-4.0 reflection extension-methods


    【解决方案1】:

    您正在尝试查找名为 SelectedItem.Text 的属性,但该属性在给定对象上不存在(而且永远不会存在,. 是不能出现在属性名称中的保留字符)

    您可以解析您的输入,将每个方法按. 拆分,然后将您的调用一个接一个地链接起来:

    public static string GetValueFromProperty(this object obj, string Name)
    {
      var methods = Name.Split('.');
    
      object current = obj;
      object result = null;
      foreach(var method in methods)
      {
        var prop = current.GetType().GetProperty(method);
        result = prop != null ? prop.GetValue(current, null) : null;
        current = result;
      }
      return result == null ? string.Empty : result.ToString();
    }
    

    现场示例here

    编辑:

    互惠的 setter 方法看起来非常相似(我在要设置的属性的类型上使其通用):

    public static void SetValueFromProperty<T>(this object obj, string Name, T value)
    {
      var methods = Name.Split('.');
    
      object current = obj;
      object result = null;
      PropertyInfo prop = null;
      for(int i = 0 ; i < methods.Length - 1  ; ++i)
      {
        var method = methods[i];
        prop = current.GetType().GetProperty(method);
        result = prop != null ? prop.GetValue(current, null) : null;
        current = result;
      }
    
      if(methods.Length > 0)
        prop = current.GetType().GetProperty(methods[methods.Length - 1]);
      if(null != prop)
          prop.SetValue(current, value, null);
    }
    

    【讨论】:

    • 谢谢它工作正常。您能否为这些属性添加设置值的代码?谢谢
    • 用二传手编辑。请注意,我没有检查传递的字符串是否符合要求。
    【解决方案2】:

    快速代码(遍历树):

    public static string GetValueFromProperty(this object obj, string Name)
    {
        string[] names = Name.Split('.');
        object currentObj = obj;
        string value = null;
        for (int i = 0; i < names.Length; i++)
        {
            string name = names[i];
            PropertyInfo prop = currentObj.GetType().GetProperty(name);
            if (prop == null)
                break;
            object propValue = prop.GetValue(currentObj, null);
            if (propValue == null)
                break;
            if (i == names.Length - 1)
                value = (string)propValue;
            else
                currentObj = propValue;
        }
        return value ?? string.Empty;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多