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

后端 未结 4 500
感动是毒
感动是毒 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:36

    I think the example below covers a lot of use cases that one would expect from ValueType. The parameter type of T? allows nullables, and the type constraints restrict it to structs that implement IFormattable which is true for the common value types I can think of.

    public void foo(T? a) where T : struct, IFormattable
    

    Note that this allows types such as decimal, datetime, timespan.

    https://docs.microsoft.com/en-us/dotnet/api/system.iformattable?view=netcore-3.1

提交回复
热议问题