C# 中的数组与泛型

Arrays vs Generic in C#

我注意到数组在 c# 中实现了 ICollection<T>。数组如何实现通用容器接口,但本身不是通用的?我们也可以这样做吗?

编辑:我还想知道数组为何不是通用的,但它接受任何类型并具有类型安全性。

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

这是一个很好的例子,它展示了我们可以从泛型创建非泛型(谢谢 MarcinJuraszek!!)。这个集合会被字符串卡住。我的猜测是它与字符串的泛型值类型声明无关,是一些我不熟悉的内部布线。

再次感谢!

是的,这完全有可能。您可以这样声明:

public class MyListOfStrings : IList<string>
{
}

并且只要您执行所有 properties/methods IList<string> 要求,一切都会正常进行。如您所见,MyListOfStrings 不是通用的。

您还应该记住,数组是特殊类型,它们会发生一些常规用户定义类型不会发生的事情。其中一些在MSDN上有描述,似乎与你的问题相关的部分在这里:

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.

如您所见,Array 以一种特殊的方式实现了 IList<T>ICollection<T>IEnumerable<T>,这不是您可以用自己的类型做的事情。