使用反射获取嵌套对象属性值 [英] Getting Nested Object Property Value Using Reflection
问题描述
我有以下两个类:
public class Address
{
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
public class Employee
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public Address EmployeeAddress { get; set; }
}
我有一个员工类的实例,如下所示:
I have an instance of the employee class as follows:
var emp1Address = new Address();
emp1Address.AddressLine1 = "Microsoft Corporation";
emp1Address.AddressLine2 = "One Microsoft Way";
emp1Address.City = "Redmond";
emp1Address.State = "WA";
emp1Address.Zip = "98052-6399";
var emp1 = new Employee();
emp1.FirstName = "Bill";
emp1.LastName = "Gates";
emp1.EmployeeAddress = emp1Address;
我有一个方法可以根据属性名称获取属性值,如下所示:
I have a method which gets the property value based on the property name as follows:
public object GetPropertyValue(object obj ,string propertyName)
{
var objType = obj.GetType();
var prop = objType.GetProperty(propertyName);
return prop.GetValue(obj, null);
}
上述方法适用于 GetPropertyValue(emp1, "FirstName")
之类的调用,但如果我尝试 GetPropertyValue(emp1, "Address.AddressLine1")
,它会抛出一个异常,因为 objType.GetProperty(propertyName);
无法定位嵌套对象的属性值.有没有办法解决这个问题?
The above method works fine for calls like GetPropertyValue(emp1, "FirstName")
but if I try GetPropertyValue(emp1, "Address.AddressLine1")
it throws an exception because objType.GetProperty(propertyName);
is not able to locate the nested object property value. Is there a way to fix this?
推荐答案
var address = GetPropertyValue(GetPropertyValue(emp1, "Address"), "AddressLine1");
对象员工没有一个名为Address.AddressLine1"的属性,它有一个名为Address"的属性,它本身有一个名为AddressLine1"的属性.
Object Employee doesn't have a single property named "Address.AddressLine1", it has a property named "Address", which itself has a property named "AddressLine1".
这篇关于使用反射获取嵌套对象属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!