Reflection, Casting List <Int32> to IEnumerable <object>
I have a class that I need to mirror through object properties and check values and other things. Everything seems to work except when I have a list and am trying to convert an item to IEnumerable.
if (propType.GetInterfaces().Contains(typeof(IEnumerable)))
{
var value = prop.GetValue(source);
Type underlyingType = propType.GetGenericArguments()[0];
var enumerable = value as IEnumerable<object>;
if(enumerable == null)
{
// problem here......
}
// Check the items in the list
}
PropType is returned as:
FullName = "System.Collections.Generic.List`1 [[System.Int32, mscorlib, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089]]"
A suitable type is returned as:
System.Int32
This works when it is a list of custom classes, it just seems to be broken when it is a value type.
Can anyone help here?
source to share
The fact that int
is a value type makes the difference here. According to the C # specification, there must be reference or identifier reference between typical types in order to make the types optionally convertible:
A type
T<A1, …, An>
is variance-convertible for a typeT<B1, …, Bn>
ifT
it is either an interface or a delegate type declared with a type variantT<X1, …, Xn>
and, for each type variant parameter,Xi
one of the following assertions:
Xi
is covariant and there is an implicit reference or identity reversal fromAi
toBi
Xi
is contravariant and there is an implicit reference or identity reversal fromBi
toAi
Xi
is invariant and there is an identical transformation fromAi
toBi
IEnumerable<T>
is covariant, so the marked line i is important. Ai
in your case int
it Bi
is int
. There is no reference conversion from int
to object
, because it is int
not a reference type. There is also no identity conversion between the two because they are not the same.
I don't know the whole context of your question, but you can use non-generic IEnumerable
instead IEnumerable<object>
. They are almost the same. However, you may run into the XY problem here, so it is difficult for you to help without knowing more about your case.
source to share