C# generic method with integer constraint refuses to cast from integer to the generic type

前端 未结 3 843
时光说笑
时光说笑 2021-01-15 04:37

If I have a generic method that is constrained to be type \'int\' then surely I should be able to cast an integer to the generic T type. For example...

    p         


        
3条回答
  •  Happy的楠姐
    2021-01-15 04:52

    int (and all other numeric types, and enums) cannot be used as a generic constraint.

    See

    Generic C# Code and the Plus Operator

    for further details and options.

    For a discussion with Anders Hejlsberg, the creator of C#, about generics and type constraints see

    http://www.artima.com/intv/generics.html

    One can place a type constraint of struct like this:

    public class Generic where T : struct { }
    
    Generic gen = new Generic();
    

提交回复
热议问题