Why can't I write Nullable>?

前端 未结 5 1131
陌清茗
陌清茗 2020-12-06 17:16

The definition of Nullable is:

[SerializableAttribute]
public struct Nullable where T : struct, new()

The constraint

5条回答
  •  感情败类
    2020-12-06 18:14

    As others have said, the spec prohibits this.

    Digging deeper, it's worth realising that you can make your own struct that allows this pattern:

    struct Nestable where T : struct { /* ... */ }
    
    new Nestable>(); // This works just fine
    

    The prohibition of nested nullables can not be expressed using the type system available to you and me. It is only enforced by a special case in the compiler (CS0453).


    Aside: The new() constraint shown in the question doesn't actually exist on System.Nullable. new() constraints are prohibited when using the struct constraint.

    CS0451: The 'new()' constraint cannot be used with the 'struct' constraint

    All structs support default initialisation anyway.

提交回复
热议问题