gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:55:42 26 4
gpt4 key购买 nike

当我尝试定义一个继承自 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com