为什么一个C#结构不能被继承?结构

2023-09-02 21:56:45 作者:薄凉旧情人

我读通过C#CLR由杰弗里里氏和它说一个结构是值类型,不能被继承。为什么不呢?任何技术方面的原因?或哲学的呢?

I am reading CLR via C# by Jeffery Richter and it says a struct is a value type and cannot be inherited. Why not? Any technical reasons? Or philosophical ones?

推荐答案

两者都有一点。

从哲学,它的作品了 - 存在着阶级,这是真正的基石面向对象编程,并有结构,这对于存储轻量级数据类型,但允许类对象方法调用的熟悉度和便利性。

Philosophically, it works out - there are classes, which are the "real" building block for object oriented programming, and there are structs, which are lightweight data types for storage but allow object-like method calls for familiarity and convenience.

技术上,是价值型意味着整个结构 - 它的所有内容 - (通常)保存无论你有一个类型的变量或成员。作为一个局部变量或函数参数,这意味着在堆栈中。为成员变量,这意味着存储完全作为对象的一部分。

Technically, being a "value type" means that the entire struct - all of it's contents - are (usually) stored wherever you have a variable or member of that type. As a local variable or function parameter, that means on the stack. For member variables, that means stored entirely as part of the object.

至于为什么继承是一个问题的一个(主)例如,考虑存储如何影响在低水平如果允许结构有亚型与多个成员。任何存储的结构类型将占用内存的基础上亚型它结束了包含,这将是一个噩梦分配可变数量。一个给定的类的对象将不再具有恒定的,在编译时已知的尺寸和相同是适用于任何方法的调用堆栈帧。这不会发生的对象,其中有存储在堆上分配,而是有固定大小的引用在堆栈或内部其他对象存储。

As a (primary) example of why inheritance is a problem, consider how storage is affected at a low level if you allowed structs to have subtypes with more members. Anything storing that struct type would take up a variable amount of memory based on which subtype it ended up containing, which would be an allocation nightmare. An object of a given class would no longer have a constant, known size at compile time and the same would be true for stack frames of any method call. This does not happen for objects, which have storage allocated on the heap and instead have constant-sized references to that storage on the stack or inside other objects.

这仅仅是一个直观的,高层次的解释 - 见注释和其他答案扩展和更precise信息

This is just an intuitive, high-level explanation - See comments and other answers for both expanded and more precise information.