I have a project that is written using c#.
I have the following object
public class ChildViewModel
{
public IEnumerable<int> Ids { get; set; }
//...
}
I want to use reflection to get the value of every property on the object. When the property is a collection, I want to be able to iterate over its values. Here is what I have done
var properties = typeof(ChildViewModel).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.CanRead && x.CanWrite);
foreach (PropertyInfo property in properties)
{
object value = property.GetValue(model, null);
if(property.PropertyType.IsArray ||
(property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition().Equals(typeof(IEnumerable<>))))
{
// Now we know that the property is a collection
// Get the value of the property
IEnumerable<object> values = value as IEnumerable<object>;
// Now, I want to iterate over the values
// somehow, I want to case values to IEnumerable<object> so I can iterate over the values
}
}
However, the variable values
is always NULL
. Here is a fiddler that I created which fails when casting IEnumerale<int>
to IEnumerable<object>
https://dotnetfiddle.net/P99hh4
How can I cast an object
to IEnumerable
where I can iterate over its values?
Aucun commentaire:
Enregistrer un commentaire