How do ValueTypes derive from Object (ReferenceType) and still be ValueTypes?

后端 未结 6 1791
闹比i
闹比i 2020-11-22 17:20

C# doesn\'t allow structs to derive from classes, but all ValueTypes derive from Object. Where is this distinction made?

How does the CLR handle this?

6条回答
  •  悲哀的现实
    2020-11-22 18:05

    Your statement is incorrect, hence your confusion. C# does allow structs to derive from classes. All structs derive from the same class, System.ValueType

    So let's try this:

     struct MyStruct :  System.ValueType
     {
     }
    

    This will not even compile. Compiler will remind you "Type 'System.ValueType' in interface list is not an interface".

    When decompile Int32 which is a struct, you will find :

    public struct Int32 : IComparable, IFormattable, IConvertible {}, not mentionning it is derived from System.ValueType. But in object browser, you do find Int32 does inherit from System.ValueType.

    So all these lead me to believe:

    I think the best way to answer this is that ValueType is special. It is essentially the base class for all value types in the CLR type system. It's hard to know how to answer "how does the CLR handles this" because it's simply a rule of the CLR.

提交回复
热议问题