【发布时间】:2010-03-29 01:05:37
【问题描述】:
我有以下两个类:
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; }
}
我有一个员工类的实例如下:
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;
我有一个根据属性名获取属性值的方法,如下:
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); 无法定位嵌套对象属性值。有没有办法解决这个问题?
【问题讨论】:
标签: c# asp.net reflection