كيف سأفعل الحفر الملكية إلى أسفل؟
-
05-07-2019 - |
سؤال
وكيف أعرف إذا مثيل كائن خاصية أو خاصية فرعية من مثيل كائن آخر؟
وعلى سبيل المثال لدي هذه البنية الطبقية:
public class Car
{
public Manufacturer Manufacturer {get;set;}
}
public class Manufacturer
{
public List<Supplier> {get;set;}
}
public class Supplier
{
string SupplierName {get;set;}
}
وليس لدي سوى حالتين، والسيارات وSupplierName. باستخدام PropertyInfo في التفكير، كيف يمكنني تنفيذ طريقة مثل
bool IsPropertyOrSubPropertyOf(object ObjectInstance, object TargetObejectInstance)
وتستخدم
IsPropertyOrSubPropertyOf(SupplierNameInstance, CarInstance)
وهذه الطريقة سوف يعود صحيحا إذا كان CarInstance في المصنع الملكية لديها مورد له SupplierName SupplierNameInstance
المحلول
هل هذا فعل ما أبحث عن؟ آسف إذا ليست أنظف - ربما كنت تريد أن تضيف بعض الشيكات فارغة في هناك، وكذلك
private bool IsPropertyOrSubPropertyOf(Object Owner, Object LookFor)
{
if (Owner.Equals(LookFor))
{
// is it a property if they are the same?
// may need a enum rather than bool
return true;
}
PropertyInfo[] Properties = Owner.GetType().GetProperties();
foreach (PropertyInfo pInfo in Properties)
{
var Value = pInfo.GetValue(Owner, null);
if (typeof(IEnumerable).IsAssignableFrom(Value.GetType()))
{
// Becomes more complicated if it can be a collection of collections
foreach (Object O in (IEnumerable)Value)
{
if (IsPropertyOrSubPropertyOf(O, LookFor))
return true;
}
}
else
{
if (IsPropertyOrSubPropertyOf(Value, LookFor))
{
return true;
}
}
}
return false;
}
وتحرير: أنا فقط لاحظت انه اذا LookFor
هو IEnumerable
ثم قد ينتهي بك الأمر مع قضية، سيترك لك لفرز؛)
نصائح أخرى
ويجب أن لا تحتاج إلى استخدام انعكاس للمثال معين تصفون:
bool IsPropertyOrSubPropertyOf(Supplier supplierInstance, Car carInstance)
{
return carInstance.Manufacturer.Suppliers.Contains(supplierInstance);
}
و(بالمناسبة، هل غاب اسم الملكية List<Supplier>
في الصف Manufacturer
الخاص بك. لقد افترض أنه يدعى في الواقع Suppliers
في قانون بلدي أعلاه).