首頁 >後端開發 >C++ >如何將.NET中的通用類型限制為僅接受數字類型?

如何將.NET中的通用類型限制為僅接受數字類型?

Patricia Arquette
Patricia Arquette原創
2025-02-01 23:36:13982瀏覽

How Can I Constrain Generic Types in .NET to Only Accept Numeric Types?

限制.net generics to Numeric類型

.NET仿製藥具有類型的靈活性,但通常需要類型的約束。 經常需要的是將通用類型參數限制為數字類型,例如Int16>,Int32Int64UInt16UInt32UInt64

>

>

>較早版本缺乏直接解決方案,但.NET 7引入(inINumber<T>)作為所有數字類型的最全面的接口。對於整數類型,可用System.NumericsIBinaryInteger<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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn