JIT 编译器如何编译泛型?
我知道泛型是由 JIT 编译的(就像其他所有东西一样),这与编译代码时生成的模板不同。
问题是,可以使用反射在运行时创建新的泛型类型。
这当然会影响泛型的约束。其中已经通过了语义解析器。
有人可以解释一下这是如何处理的吗?到底发生了什么?
(代码生成和语义检查)
I know that generics are compiled by JIT (like everything else), in contrast to templates that are generated when you compile the code.
The thing is that new generic types can be created in runtime by using reflection.
Which can of course affect the generic's constraints. Which already passed the semantic parser.
Can someone explain how this is handled ? And what exactly happens ?
(Both the code generation and semantic check)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议阅读C#、Java 和 C++ 中的泛型:与 Anders Hejlsberg 的对话。
来自采访:
本质上,IL 保留了泛型类型的高级视图,这允许 CLR 在运行时检查“动态构造”泛型类型的约束,就像 C# 编译器在 C# 源代码中对“静态构造”类型所做的那样。编译时。
这是另一个片段(强调我的):
I recommend reading Generics in C#, Java, and C++: A Conversation with Anders Hejlsberg.
From the interview:
Essentially, IL retains a high-level view of generic types, which allows the CLR to check constraints for 'dynamically constructed' generic types at run-time just like the C# compiler might do for 'statically constructed' types in C# source-code at compile-time.
Here's another snippet (emphasis mine):
引用类型泛型全部变成相同类型;值类型泛型是单独实例化的。
这是因为引用类型实际上都只是
Object
引用(4 或 8 字节),而值类型则不同,并且由于堆栈布局差异等原因,不能由单段代码处理。因此,使用值类型实例化泛型类型的多个副本会大量增加内存使用量,而使用引用类型实例化多个副本则不会。Reference types generics all become the same type; value type generics are instantiated separately.
This is because reference types are all really just
Object
references (4 or 8 bytes), whereas value types are different and cannot be handled by a single piece of code, due to stack layout differences, etc. Therefore, instantiating multiple copies of a generic type with value types will increase the memory usage by a lot, whereas instantiating multiple copies with reference types won't.