为什么C#结构不能被继承? [英] Why C# structs cannot be inherited?

查看:278
本文介绍了为什么C#结构不能被继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Jeffery Richter通过C#编写的CLR,它说一个结构是一种值类型,不能继承。

I am reading CLR via C# by Jeffery Richter and it says a struct is a value type and cannot be inherited.

是否存在任何技术或哲学原因?

Are there any technical or philosophical reasons?

推荐答案

编辑:显然,该帖子存在严重的编辑问题。见评论部分。

There are serious editorial concerns about this post, apparently. See comment section.

两者都有一点。

从哲学上来说,它可以正常工作外面-有一些类,它们是面向对象编程的真正构建基块,还有一些结构,它们是用于存储的轻量数据类型,但允许类似对象的方法调用,以提高熟悉性和便利性。

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 its 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.

作为继承问题的一个(主要)示例,请考虑如果允许结构具有更多成员的子类型,那么在较低级别上如何影响存储。任何存储该struct类型的内容都会根据其最终包含的子类型占用可变数量的内存,这将是分配的噩梦。给定类的对象在编译时将不再具有恒定的已知大小,并且任何方法调用的堆栈帧都将具有相同的大小。对于那些在堆上分配了存储,而是在堆栈上或其他对象内部具有对该存储的恒定大小引用的对象,则不会发生这种情况。

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.

直观,高级的解释-有关扩展且更精确的信息,请参阅评论和其他答案。

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

这篇关于为什么C#结构不能被继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆