C# Reflection on Nested Properties of a Class
I wanted to know how can I get the Value of Property in C#, but this property is of another Type.
public class Customer
{
public string Name {get; set;}
public string Lastname {get; set;}
public CustomerAddress Address {get; set;}
}
So I'm able to get the property values of Name and LastName but I quite don't get how to get the value of CustomerAddress.City.
This is what I have until now.
public object GetPropertyValue(object obj, string property)
{
if (string.IsNullOrEmpty(property))
return new object { };
PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
return propertyInfo.GetValue开发者_高级运维(obj, null);
}
Then is use this method in a LINQ statement.
var cells = (from m in model
select new
{
i = GetPropertyValue(m, key),
cell = from c in columns
select reflection.GetPropertyValue(m, c)
}).ToArray();
So I get no value for the CustomerAddress.
Any help will be deeply appreciated.
**** UPDATE ****
Here how I managed to do it.
public object GetNestedPropertyValue(object obj, string property)
{
if (string.IsNullOrEmpty(property))
return string.Empty;
var propertyNames = property.Split('.');
foreach (var p in propertyNames)
{
if (obj == null)
return string.Empty;
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(p);
if (info == null)
return string.Empty;
obj = info.GetValue(obj, null);
}
return obj;
}
First off, if you want to get the value of CustomerAddress.City
, you will never get it. CustomerAddress
is the type, not the property name. You want to get Address.City
.
That said, your GetPropertyValue
is not set up to do what you want.
Try splitting the name by the dots:
var propertyNames = property.split('.');
Now, you have a list of the property names {"Address", "City"}
Then, you can loop through these property names, one by one, calling GetPropertyValue
recursively.
That should do it :)
@Michael -> the inverted part;-)
public static void SetNestedPropertyValue(object obj, string property,object value)
{
if (obj == null)
throw new ArgumentNullException("obj");
if (string.IsNullOrEmpty(property))
throw new ArgumentNullException("property");
var propertyNames = property.Split('.');
foreach (var p in propertyNames)
{
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(p);
if (info != null)
{
info.SetValue(obj, value);
return;
}
}
throw new KeyNotFoundException("Nested property could not be found.");
}
精彩评论