जब से तुम मनमाने ढंग से-नेस्टेड बच्चे वस्तुओं पर वस्तुओं को खोजने के लिए सक्षम होना चाहते हैं, तो आप एक समारोह है कि आप पुनरावर्ती कॉल कर सकते हैं की जरूरत है। यह इस तथ्य से जटिल है कि आपके बच्चे हो सकते हैं जो उनके माता-पिता को वापस संदर्भित करते हैं, इसलिए आपको अपनी खोज में पहले देखी गई वस्तुओं का ट्रैक रखने की आवश्यकता है।
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;
}
आप जानते हैं कि बच्चे को आपत्ति अपनी संपत्ति में आप इसे करने के लिए पथ पारित कर सकते हैं तो की तरह, यह है:
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;
}
इसके बजाय GetValue("foo", out val)
है जैसे कि यह बुलाने की आप इसे GetValue("foo.bar", out val)
की तरह कहेंगे।
क्या आपको कोई समस्या है या क्या कोई और सवाल है? – leppie
मेरे प्रश्न को संपादित किया गया है, बच्चे ऑब्जेक्ट संपत्ति मूल्य तक पहुंचने के लिए एक तरीका चाहिए। – iniki