How will I do a property drill down?
How will I know if an object instance is a property or a sub property of another object instance?
for example I have this class structure:
public class Car
{
public Manufacturer Manufacturer {get;set;}
}
public class Manufacturer
{
public List<Supplier开发者_如何学Go> {get;set;}
}
public class Supplier
{
string SupplierName {get;set;}
}
And I only have two instances, the Car and the SupplierName; Using PropertyInfo in Reflection, How can I Implement a method such as
bool IsPropertyOrSubPropertyOf(object ObjectInstance, object TargetObejectInstance)
used as
IsPropertyOrSubPropertyOf(SupplierNameInstance, CarInstance)
this method will return true if the CarInstance's Property Manufacturer has a Supplier that has a SupplierName SupplierNameInstance
Does this do what your looking for? Sorry if its not the cleanest - you will probably want to add some null checks in there as well.
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;
}
Edit: I just noticed that if LookFor
is IEnumerable
then you may end up with an issue, will leave that to you to sort out ;)
You shouldn't need to use reflection for the particular example you describe:
bool IsPropertyOrSubPropertyOf(Supplier supplierInstance, Car carInstance)
{
return carInstance.Manufacturer.Suppliers.Contains(supplierInstance);
}
(By the way, you missed out the name of the List<Supplier>
property in your Manufacturer
class. I've assumed that it's actually called Suppliers
in my code above.)
精彩评论