When I do this cast:
private IEnumerable objects;
ArrayList castedObjects = (ArrayList)objects;
Is this a "direct" cast, or the enumerable is converted into an ArrayList via an internal method (that presumably loops through all the elements)?
This is either a "direct" cast (if the underlying object is actually an instance of ArrayList
), or you'll get an exception . No implicit creating of an ArrayList
object is done "behind the scene".
This is a direct cast. It will only work if the object is an ArrayList
already, for example:
IEnumerable objects = new ArrayList();
ArrayList castedObjects = (ArrayList)objects;
If the object is not an ArrayList
but some other object that implements IEnumerable
, the cast will fail.
You can create an ArrayList
from an ICollection
, for example:
ICollection objects = new string[] { "a", "b" };
ArrayList castedObjects = new ArrayList(objects);
This will loop through the collection and copy the items to the ArrayList
, so it's an O(n) operation.
Generally you should not use the ArrayList
class at all, but the generic List<T>
class that offers strict typing.
It depends on what objects
actually is. It is referenced as an IEnumerable
, but its actual type may be anything that implements IEnumerable
.
If the reference can be cast to an ArrayList
(because it already is, or inherits from, ArrayList
) then it is O(1). If it cannot, then you'll just get an exception.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.