Почему индекс ICollection не работает при инстанцировании?

При выполнении этого в целях совместимости сети/хоста, необходимо использовать:

ntohl() //Network to Host byte order (Long)
htonl() //Host to Network byte order (Long)

ntohs() //Network to Host byte order (Short)
htons() //Host to Network byte order (Short)

при выполнении этого по некоторой другой причине одно из byte_swap решений, представленных здесь, работало бы просто великолепно.

20
задан demokritos 10 December 2009 в 11:11
поделиться

4 ответа

The ICollection interface doesn't declare an indexer, so you can't use indexing to fetch elements through a reference of that type.

You could perhaps try IList, which adds some more functionality, while still being abstract. Of course, this may impact other design decisions so I would look at this carefully.

28
ответ дан 29 November 2019 в 22:34
поделиться

The basic problem is that ICollection doesn't define an index. For the List this is done by the implementation of IList.

Try this:

IList<ProductDTO> Products = new List<ProductDTO>(); 

Alternatly, you can keep using ICollection and convert to an array when you need to access the elements by the index:

ICollection<ProductDTO> Products = new List<ProductDTO>();        
ProductDTO z = Products.ToArray()[0];
3
ответ дан 29 November 2019 в 22:34
поделиться

Then this will work:

ProductDTO product = ((IList<ProductDTO>)Products)[0];

The reason is that the compiler evaluates the lvalue, that is the variable on the left side of '=', to find out which methods and properties it knows it can access at compile-time. This is known as static typing, and ensures that an object member can be accessed directly at runtime by statically knowing that the member is always reachable.

5
ответ дан 29 November 2019 в 22:34
поделиться

ICollection does not define an indexer.

ICollection Non-Generic

ICollection Generic

7
ответ дан 29 November 2019 в 22:34
поделиться
Другие вопросы по тегам:

Похожие вопросы: