Rasgele yuvalanmış alt nesneler üzerinde nesneleri bulmak istediğiniz için, yinelemeli olarak çağırabileceğiniz bir işleve ihtiyacınız vardır. Bu, ebeveynlerine geri dönen çocuklarınız olabileceği için karmaşıktır, dolayısıyla aramanızda daha önce gördüğünüz nesneleri izlemeniz gerekir.
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;
}
size özelliği sadece bu yüzden gibi, bunun yolunu iletebilirsiniz olduğunu hangi nesne çocuk biliyorsanız
:
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;
}
yerine GetValue("foo", out val)
gibi çağıran sen GetValue("foo.bar", out val)
gibi çağırır.
Başka bir sorunuz mu var? – leppie
sorumu düzenledim, child object özellik değerine erişmenin bir yoluna ihtiyacım var. – iniki