I have an array of an anonymous type declared as:
var list = new[]
{
new {Name = "A", Age = 10},
new {Name = "B", Age = 15}
}
Now list inherits from type Array, which implements IEnumerable. Why does the following fail:
Convert.ChangeType(list, typeof(IEnumerable));
This also fails:
Convert.ChangeType(list, typeof(Array));
Kind regards,开发者_如何转开发
The Convert.ChangeType
method requires an implementation of IConvertible
- essentially a declaration of how to convert from the source type to the target type. System.Array
does not implement the IConvertible
interface.
What you are trying to do is cast from one type to another, and (IEnumerable)list
works perfectly well.
Edit:
As Jon says, the cast here is implicit, so simple assignment (ie implicit cast) to an IEnumerable also works.
Just use the implicit conversion and it's fine:
IEnumerable enumerable = list;
As Nader says, Convert.ChangeType
works with IConvertible
. Personally I can't remember the last time I used it - I would stick with simple casts etc where possible.
精彩评论