我有以下两个类:
我有一个Employee类的实例,如下所示。
我有一个方法,根据属性名称获取属性值,如下所示:
在上述方法中,当我尝试获取嵌套类的属性值时,可以按以下方式操作:
或者
public class Family
{
public string ChildName { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public Family Child { get; set; }
}
我有一个Employee类的实例,如下所示。
Employee employee = new Employee();
employee.Name = "Ram";
employee.Id = 77;
employee.Child = new Family() { ChildName = "Lava" };
我有一个方法,根据属性名称获取属性值,如下所示:
public static object GetPropertyValue(object src, string propName)
{
string[] nameParts = propName.Split('.');
if (nameParts.Length == 1)
{
return src.GetType().GetRuntimeProperty(propName).GetValue(src, null);
}
foreach (String part in nameParts)
{
if (src == null) { return null; }
Type type = src.GetType();
PropertyInfo info = type.GetRuntimeProperty(part);
if (info == null)
{ return null; }
src = info.GetValue(src, null);
}
return src;
}
在上述方法中,当我尝试获取嵌套类的属性值时,可以按以下方式操作:
GetPropertyValue(employee, "employee.Child.ChildName")
或者
GetPropertyValue(GetPropertyValue(employee, "Family"), "ChildName"
因为type.GetRuntimeProperty(part)
始终为空,所以不返回任何值。
有没有办法解决这个问题?