How to Convert IList<SomeObject> to IList<ISomeInterface> where SomeObject implements ISomeInterface using covariance in C# 4.0

假如想象 提交于 2019-12-07 18:54:52

问题


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#


回答1:


why not simply use

IList<Items> GetItems;
IList<IItems> items = GetItems().Cast<IItems>().ToList(); 



回答2:


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




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!