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

前端 未结 3 822
时光说笑
时光说笑 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条回答
  • 2021-01-15 04:44

    "Only class or interface could be specified as constraint." (c) ReSharper

    int (Int32) is just a struct. You can constrain that T is a struct. but you can't use any struct as constraint.

    the whole list of possible constraints you can find here - http://msdn.microsoft.com/en-us/library/d5x73970.aspx

    UPD

    and for Enum constraint see this question - Is there a workaround for generic type constraint of "special class" Enum in C# 3.0?

    0 讨论(0)
  • 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<T> where T : struct { }
    
    Generic<int> gen = new Generic<int>();
    
    0 讨论(0)
  • 2021-01-15 05:01

    Are you sure its compiling?

    Here, it gives following error:

    error CS0701: 'int' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.

    0 讨论(0)
提交回复
热议问题