C#generic method's constraints of specific numerical types
When using generics in C#, is there a constraint that can limit the type parameter T to only the following values type: int16, int32, int64, UINT16, UINT32, and UINT64?
Answer
In .NET 7, an interface specially used to limit T to numerical types:
in the name space. To accept only the integer type, you can use. System.Numerics
INumber<T>
Considering the following Method implementation: IBinaryInteger<T>
How to use examples: IntegerFunction
static bool IntegerFunction<T>(T value) where T : IBinaryInteger<T> { return value > T.Zero; }
Console.WriteLine(IntegerFunction(5)); // True Console.WriteLine(IntegerFunction((sbyte)-5)); // False Console.WriteLine(IntegerFunction((ulong)5)); // True
For scenes that are unavailable directly to support constraints, it is recommended to use alternative methods, such as factory models or strategies.
The above is the detailed content of Can C# Generics Constrain Type Arguments to Specific Integer Types?. For more information, please follow other related articles on the PHP Chinese website!