How to Convert IList to IList where SomeObject implements ISomeInterface using covariance in C# 4.0
I have something similar to following
IList<Items> GetItems;
IList<IItems> items = GetItems() as IList<IItems>;
but items is null;
the answer here was for pre 4.0:
Converting an array of type T to an array of type I where T implements I in C#
why not simply use
IList<Items> GetItems;
IList<IItems> items = GetItems().Cast<IItems>().ToList();
For this to work as you are thinking then I believe IList would have to be declared as covariant, not the items in the list. And IList does not support covariance. The only .NET interfaces that were updated to support covariance are:
- IEnumerable (T is covariant)
- IEnumerator (T is covariant)
- IQueryable (T is covariant)
- IGrouping (TKey and TElement are covariant)
- IComparer (T is contravariant)
- IEqualityComparer (T is contravariant)
- IComparable (T is contravariant)
This from http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx
Technically, the following will work, but I don't think this is exactly what you're looking for...
IList<IItems> items = GetItems().ToArray() as IList<IItems>;
来源:https://stackoverflow.com/questions/5602400/how-to-convert-ilistsomeobject-to-ilistisomeinterface-where-someobject-imple