How can I convert a generic List<T> to a List?
How can I convert a generic List to a List?
I am using a ListCollectionView
and I need to provide it with an IList
not an IList<T>
.
I see plenty of examples to convert an IList
to a IList<T>
, but 开发者_JS百科not the other way.
Do I just convert it manually (new List().AddRange(IList<T>
)?
To clarify the other answers:
IList<T>
does not require an implementing type to also implement IList
. IEnumerable<T>
does require IEnumerable
. We can get away with that with IEnumerable<T>
because a sequence of T can always be treated as a sequence of objects. But a list of giraffes cannot be treated as a list of objects; you can add a tiger to a list of objects.
However, List<T>
does unsafely implement IList
. If you try to add a tiger to a List<Giraffe>
by first casting it to IList, you'll get an exception.
So to answer the question: If all you have in hand is an IList<T>
, you can speculatively cast it to IList
with the "as" operator, and if that fails, then create a new ArrayList
or List<object>
and copy the contents in. If what you have in hand is a List<T>
then you already have something that implements IList
directly.
As List<T>
implements the IList
interface, you can simply provide the List<T>
. If needed, just cast it:
List<int> list = new List<int>();
IList ilist = (IList)list;
You don't have to do any conversion at all. A List<T>
implements the IList
interface.
If you need the type IList
for example to use a specific overload, just use the cast syntax (IList)theList
.
精彩评论