Skip to main content
 首页 » 编程设计

c#之使用反射获取二级属性值

2024年02月06日35jirigala

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

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

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