限制.net generics to Numeric类型
.NET仿制药具有类型的灵活性,但通常需要类型的约束。 经常需要的是将通用类型参数限制为数字类型,例如Int16
>,Int32
,Int64
,UInt16
,UInt32
,UInt64
,
>
>>较早版本缺乏直接解决方案,但.NET 7引入INumber<T>
)作为所有数字类型的最全面的接口。对于整数类型,可用System.Numerics
。
IBinaryInteger<T>
此示例使用
>:IntegerFunction
>
IBinaryInteger<T>
<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>> pre-.net 7方法
.NET 7之前,实现此限制更具挑战性。 建议使用类的工厂模式,但这些方法的建议是不优雅且不太延伸的代码。
>以上是如何将.NET中的通用类型限制为仅接受数字类型?的详细内容。更多信息请关注PHP中文网其他相关文章!