Vì bạn muốn có thể tìm thấy các đối tượng trên các đối tượng con tùy ý lồng nhau, bạn cần một hàm mà bạn có thể gọi đệ quy. Điều này là phức tạp bởi thực tế là bạn có thể có trẻ em tham khảo lại cha mẹ của họ, vì vậy bạn cần phải theo dõi các đối tượng mà bạn đã nhìn thấy trước đó trong tìm kiếm của bạn.
static bool GetValue(object currentObject, string propName, out object value)
{
// call helper function that keeps track of which objects we've seen before
return GetValue(currentObject, propName, out value, new HashSet<object>());
}
static bool GetValue(object currentObject, string propName, out object value,
HashSet<object> searchedObjects)
{
PropertyInfo propInfo = currentObject.GetType().GetProperty(propName);
if (propInfo != null)
{
value = propInfo.GetValue(currentObject, null);
return true;
}
// search child properties
foreach (PropertyInfo propInfo2 in currentObject.GetType().GetProperties())
{ // ignore indexed properties
if (propInfo2.GetIndexParameters().Length == 0)
{
object newObject = propInfo2.GetValue(currentObject, null);
if (newObject != null && searchedObjects.Add(newObject) &&
GetValue(newObject, propName, out value, searchedObjects))
return true;
}
}
// property not found here
value = null;
return false;
}
Nếu bạn biết những gì con phản đối tài sản của bạn là ở bạn chỉ có thể vượt qua các đường dẫn đến nó, như vậy:
public bool GetValue(string pathName, out object fieldValue)
{
object currentObject = _currentObject;
string[] fieldNames = pathName.Split(".");
foreach (string fieldName in fieldNames)
{
// Get type of current record
Type curentRecordType = currentObject.GetType();
PropertyInfo property = curentRecordType.GetProperty(fieldName);
if (property != null)
{
currentObject = property.GetValue(currentObject, null).ToString();
}
else
{
fieldValue = null;
return false;
}
}
fieldValue = currentObject;
return true;
}
Thay vì gọi nó như GetValue("foo", out val)
bạn sẽ gọi nó như GetValue("foo.bar", out val)
.
Bạn có gặp sự cố hoặc có câu hỏi khác ở đây không? – leppie
đã chỉnh sửa câu hỏi của tôi, cần một cách để truy cập giá trị thuộc tính đối tượng con. – iniki