我有以下兩類:獲取嵌套的對象屬性值使用反射
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);
無法找到嵌套的對象屬性值。有沒有辦法來解決這個問題?
這是迴應其他答案嗎? – 2012-10-26 04:51:51
這不適用於2級屬性 – SyntaxGoonoo 2014-08-06 02:58:21
就像一個魅力工作! – 2017-06-01 08:39:28