Is there a constraint that restricts my generic method to numeric types?

后端 未结 21 2591
栀梦
栀梦 2020-11-21 05:48

Can anyone tell me if there is a way with generics to limit a generic type argument T to only:

  • Int16
  • Int32
21条回答
  •  渐次进展
    2020-11-21 06:12

    Beginning with C# 7.3, you can use closer approximation - the unmanaged constraint to specify that a type parameter is a non-pointer, non-nullable unmanaged type.

    class SomeGeneric where T : unmanaged
    {
    //...
    }
    

    The unmanaged constraint implies the struct constraint and can't be combined with either the struct or new() constraints.

    A type is an unmanaged type if it's any of the following types:

    • sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool
    • Any enum type
    • Any pointer type
    • Any user-defined struct type that contains fields of unmanaged types only and, in C# 7.3 and earlier, is not a constructed type (a type that includes at least one type argument)

    To restrict further and eliminate pointer and user-defined types that do not implement IComparable add IComparable (but enum is still derived from IComparable, so restrict enum by adding IEquatable < T >, you can go further depending on your circumstances and add additional interfaces. unmanaged allows to keep this list shorter):

        class SomeGeneric where T : unmanaged, IComparable, IEquatable
        {
        //...
        }
    

    But this doesn't prevent from DateTime instantiation.

提交回复
热议问题