Why can't I use System.ValueType as a generics constraint?

后端 未结 4 515
感动是毒
感动是毒 2020-12-24 05:18
  • Why can\'t I use a constraint of where T : System.ValueType?
  • Why does Microsoft prevent this type from being a constraint?

4条回答
  •  一个人的身影
    2020-12-24 05:56

    There are two differences between using

    where T : struct
    

    and

    where T : ValueType
    
    • the latter would allow T to be ValueType itself, which is a reference type.
    • the latter would also allow T to be a nullable value type

    The first of these differences is almost never what you want. The second could occasionally be useful; Nullable is slightly odd in that it satisfies neither the where T : struct nor where T : class constraint.

    More useful would be the constraint

    where T : struct, System.Enum
    

    which is prohibited by C# for no good reason that I can tell. See my blog post and the Unconstrained Melody project for more on this.

提交回复
热议问题