簡體   English   中英

使用反射獲取二級屬性值

[英]Get second level property value using reflection

我寫了一個擴展方法來獲取對象的屬性值,這是該代碼:

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

但是它不返回任何東西。

我如何擴展從第二級屬性(或一般形式的任何級別)返回值的擴展方法?

謝謝

您試圖找到一個名為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();
}

這里的例子。

編輯:

互惠的二傳手方法看起來非常相似(我對要設置的屬性類型進行了通用設置):

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

快速代碼(遍歷樹):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM