Fixed: IList <T> for a custom class that implements ICollection <T>

This is my custom collection ad.

public interface IMenuCollection<T> : ICollection<T>
public class HTMLMenuCollection: IMenuCollection<HTMLMenu>

I am trying to transfer it from another collection IList<T>.

IList<HTMLMenu> htmlMenuList = new List<HTMLMenu>();
...
HTMLMenuCollection tempColl = (HTMLMenuCollection)htmlMenuList;

I have no idea why this will not work. If I drop IList<T>in ICollection<T>, it works fine, but with this I get an invalid lit exception. What am I doing wrong?

+3
source share
5 answers

Think of inheritance as an “is” relationship.

, HTMLMenuCollection List<HTMLMenu>, List<HTMLMenu> HTMLMenuCollection ( List<HTMLMenu> HTMLMenuCollection).

, IList ICollection, :

public class List<T> : IList<T>, ICollection<T> // and more

public interface IList<T> : ICollection<T> // and more
+5

, List<HTMLMenu> HTMLMenuCollection, .

+5

HTMLMenuCollection IList. ICollection , ICollection.

, List HTMLMenuCollection, , HTMLMenuCollection List, , , upconvert , HTMLMenuCollection, ( ), List.

, , ICollection , .

0

.net , . htmlMenuList - List<HTMLMenu>, HTMLMenuCollection, List<HTMLMenu> HTMLMenuCollection.

0

AddRange(IEnumerable<HtmlMenu>), HtmlMenuCollection ICollection<HtmlMenu>.

0

Source: https://habr.com/ru/post/1764035/


All Articles