开发者

Why can't new[] {AnonymousType, AnonymousType} be casted to IEnumerable?

开发者 https://www.devze.com 2022-12-09 07:25 出处:网络
I have an array of an anonymous type declared as: var list = new[] { new {Name = \"A\", Age = 10}, new {Name = \"B\", Age = 15}

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消