微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我在想这个.类显然是由ptr传递的.我怀疑结构是通过复制传递但我不确定. (对于一个int数组而言,将每个元素都设置为ptr并将ptrs传递给ints似乎是浪费)

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

这可能有意义,因为源将在DLL内部的CIL中.但我完全猜测,它是如何完成的?也许是ECMA标准的参考或页面#?

解决方法

泛型使用开放和封闭泛型类型的概念:参数化泛型类定义(即List< T>)是一种开放泛型类型,运行时为代码中的每个不同用途生成一个封闭的泛型类型,即不同的类型为List< int>创建了类型和列表< 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.

原文地址:https://www.jb51.cc/csharp/243394.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐