限制.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>
.NET 7之前,實現此限制更具挑戰性。 建議使用類的工廠模式,但這些方法的建議是不優雅且不太延伸的代碼。
>以上是如何將.NET中的通用類型限制為僅接受數字類型?的詳細內容。更多資訊請關注PHP中文網其他相關文章!