简体   繁体   中英

Arrays vs Generic in C#

I have noticed that array, in c#, implements ICollection<T> . How can an array implement a generic container interface, yet not be generic itself? Is it possible for us to do the same?

Edit: I would also like to know how the array is not generic, yet it accepts any type and has type safety.

public class ListOfStrings : IList<string>
{
...
}

This is a great example that demonstrates that we can create non-generics from a generic (Thank you MarcinJuraszek!!). This collection would be stuck with strings. My guess is that it has nothing to do with the generic value type declaration of string and is some internal wiring that I am unfamiliar with.

Thank you again!

Yes, it's totally possible. You can declare something like this:

public class MyListOfStrings : IList<string>
{
}

and as long as you implement all the properties/methods IList<string> requires you to everything will work just fine. As you can see MyListOfStrings is not generic.

You should also remember that Arrays are special types, and there is a bunch of stuff going on with them that's not happening with regular user-defined types. Some of it is described on MSDN , and the part that seem to be related to your questions is here:

Starting with the .NET Framework 2.0, the Array class implements the System.Collections.Generic.IList<T> , System.Collections.Generic.ICollection<T> , and System.Collections.Generic.IEnumerable<T> generic interfaces. The implementations are provided to arrays at run time, and as a result, the generic interfaces do not appear in the declaration syntax for the Array class. In addition, there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException .

As you can see Array implements IList<T> , ICollection<T> and IEnumerable<T> in a special way, and it's not something you can do with your own type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM