How are the “primitive” types defined non-recursively?

前端 未结 3 2012
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 19:28

Since a struct in C# consists of the bits of its members, you cannot have a value type T which includes any T fields:

         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-15 19:57

    Three remarks, in addition to thecoop's answer:

    1. Your assertion that recursive structs inherently couldn't work is not entirely correct. It's more like a statement "this statement is true": which is true if it is. It's plausible to have a type T whose only member is of type T: such an instance might consume 0 bytes, for example (since its only member consumes 0 bytes). Recursive value types only stop working if you have a second member (which is why they are disallowed).

    2. Take a look at Mono's definition of Int32. As you can see: it actually is a type containing itself (since int is just an alias for Int32 in C#). There is certainly "black magic" involved (i.e. special-casing), as the comments explain: the runtime will lookup the field by name, and just expect that it's there - I also assume that the C# compiler will special-case the presence of int here.

    3. In PE assemblies, type information is represented through "type signature blobs". These are sequences of type declarations, e.g. for method signatures, but also for fields. The list of available primitive types in such a signature is defined in section 22.1.15 of the CLR specification; a copy of the allowed values is in the CorElementType enumeration. Apparently, the reflection API maps these primitive types to their corresponding System.XYZ valuetypes.

提交回复
热议问题