gpt4 book ai didi

c# - 泛型如何实现结构?

转载 作者:太空狗 更新时间:2023-10-29 21:10:35 26 4
gpt4 key购买 nike

我正在考虑这个问题。类显然是由 ptr 传递的。我怀疑结构是通过复制来传递的,但我不确定。 (对于一个 int 数组来说,让每个元素都有一个 ptr 似乎是一种浪费。并为 int 传递 ptrs)

不过想想,List<MyStruct>无法知道我的结构的大小。当我这样做时会发生什么?是否有“List`1”的多个副本,每次我使用它的存储大小时,它都没有创建一个新的实现? (针对 T 等的新偏移量进行调整)。

这是有道理的,因为源代码位于 DLL 内的 CIL 中。但我完全在猜测,它是怎么做到的?也许是对 ECMA 标准的引用或页码?

最佳答案

泛型使用开放和封闭泛型的概念:参数化泛型类定义(即 List<T> )是一种开放泛型,运行时会为代码中的每种不同用途生成封闭泛型,即为 List<int> 创建了不同的类型和 List<MyStruct> - 对于每个封闭的通用类型,T 的大小和类型在运行时已知。

来自 MSDN 的澄清:

When a generic type or method is compiled into Microsoft intermediate language (MSIL), it contains metadata that identifies it as having type parameters. How the MSIL for a generic type is used differs based on whether the supplied type parameter is a value type or reference type.

When a generic type is first constructed with a value type as a parameter, the runtime creates a specialized generic type with the supplied parameter or parameters substituted in the appropriate locations in the MSIL. Specialized generic types are created one time for each unique value type that is used as a parameter.

Generics work somewhat differently for reference types. The first time a generic type is constructed with any reference type, the runtime creates a specialized generic type with object references substituted for the parameters in the MSIL. Then, every time that a constructed type is instantiated with a reference type as its parameter, regardless of what type it is, the runtime reuses the previously created specialized version of the generic type. This is possible because all references are the same size.

关于c# - 泛型如何实现结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6431834/

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