c# - 是什么让 ValueType 类特别?

标签 c# inheritance compiler-errors

当我尝试定义一个继承自 System.ValueTypeSystem.Enum 类的类时,出现错误:

Cannot derive from special class System.ValueType

我理解那个错误,但我不明白是什么让 ValueType特殊?我的意思是没有关键字(如sealed)或属性来指定此类不能被继承。ValueType 有两个属性,SerializableComVisible 但它们都与该案例无关。documentation说:

Although ValueType is the implicit base class for value types, you cannot create a class that inherits from ValueType directly. Instead, individual compilers provide a language keyword or construct (such as struct in C# and Structure…End Structure in Visual Basic) to support the creation of value types.

但它没有回答我的问题。所以我的问题是在这种情况下如何通知编译器?当我尝试创建一个继承自某个类的类时,编译器是否会直接检查该类是 ValueType 还是 Enum

编辑:所有结构隐式继承自ValueType,但Enum显式继承自 ValueType,那么它是如何工作的呢?编译器是怎么弄清楚这种情况的,所有这些都是编译器硬编码的?

最佳答案

I understand that error but what I couldn't understand is what makes ValueType class special?

该类被记录为特殊类。这就是它的特别之处。

how the compiler is informed in this case?

编译器编写者在编写编译器之前阅读文档。

Does the compiler directly check whether the class is ValueType or Enum when I try to create a class that inherit from a class?

是的。

Also all structs implicitly inherit from ValueType, but Enum class Explicitly inherit from ValueType, so how is that working?

它运行良好。

Are all of these special cases hard coded into the compiler?

是的。

Isn't it more appropriate to create an attribute to specify that this class is special and cannot be inherited instead of hard coding?

不,不是。这意味着第三方也可以创建一个特殊类型,在继承时需要编译器进行特殊处理。第三方将如何修改编译器以实现这些规则?

关于c# - 是什么让 ValueType 类特别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21213708/

相关文章:

c# - 抽象类和接口(interface)中可以使用相同的字段名称吗?

c# - ASP.NET MVC 为什么需要调用父类的空虚方法

lua - 无法确定此文件的Lua格式

c# - 在 Silverlight 4 OOB 中恢复文件下载

c# - MongoDB:推荐在 .NET 上使用的驱动程序?

c# - SSL 端口 5671 上的 RabbitMQ 无法访问,但可在 telnet 上访问

c# - 检查 ASP.NET Core 1.0 中的 session

class - 使用JavaScript ES6/ES2015子类化时如何覆盖继承的方法

ruby-on-rails - 在scss中编译错误

c++ - 奇怪的代码破坏了 MSVC 中的构建。这是什么意思?