C#泛型方法对特定数值类型的约束
在C#中使用泛型时,是否存在一种约束可以将类型参数T限制为仅包含以下数值类型:Int16、Int32、Int64、UInt16、UInt32和UInt64?
解答
在.NET 7中,引入了一个专门用于将T限制为数值类型的接口:System.Numerics
命名空间中的INumber<T>
。要仅接受整数类型,可以使用IBinaryInteger<T>
。
考虑以下IntegerFunction
方法的实现:
<code class="language-csharp">static bool IntegerFunction<T>(T value) where T : IBinaryInteger<T> { return value > T.Zero; }</code>
使用方法示例:
<code class="language-csharp">Console.WriteLine(IntegerFunction(5)); // True Console.WriteLine(IntegerFunction((sbyte)-5)); // False Console.WriteLine(IntegerFunction((ulong)5)); // True</code>
历史背景
在.NET 7之前,C#没有提供这样的约束。正如Anders Hejlsberg解释的那样,原因是为了避免不必要的复杂性,而实际好处有限。
对于直接支持约束不可用的场景,建议使用替代方法,例如工厂模式或策略类。
以上是c#generics可以将类型的参数限制为特定的整数类型吗?的详细内容。更多信息请关注PHP中文网其他相关文章!