gpt4 book ai didi

c# - C# 中的数组与泛型

转载 作者:行者123 更新时间:2023-11-30 14:26:19 25 4
gpt4 key购买 nike

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

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

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

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

再次感谢!

最佳答案

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

public class MyListOfStrings : IList<string>
{
}

只要你实现了所有的属性/方法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>以一种特殊的方式,这不是你可以用你自己的类型来做的事情。

关于c# - C# 中的数组与泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35713924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com