我认为通用算术是 .NET 语言中的常见问题。有很多文章解释了不同的方法,很快我将发布另一篇解释我的文章,它与您发布的解决方案相似。
现在,如果你问我是否应该使用它,我会说:只要你明白你在做什么,为什么不呢?我在生产中部分使用它并且完全没有问题,但是因为我关心运行时性能,所以我使用重载在编译时解决所有问题。然后为了加快编译时间,我重新定义了基本的数学运算符以在相同的类型中运行,否则类型签名会变得非常复杂并且可能需要很长时间才能编译。
还有更多需要考虑的事情,但对于您的具体问题,这里有一个示例代码:
open System.Numerics
type FromInt = FromInt with
static member ($) (FromInt, _:sbyte ) = fun (x:int) -> sbyte x
static member ($) (FromInt, _:int16 ) = fun (x:int) -> int16 x
static member ($) (FromInt, _:int32 ) = id
static member ($) (FromInt, _:float ) = fun (x:int) -> float x
static member ($) (FromInt, _:float32 ) = fun (x:int) -> float32 x
static member ($) (FromInt, _:int64 ) = fun (x:int) -> int64 x
static member ($) (FromInt, _:nativeint ) = fun (x:int) -> nativeint x
static member ($) (FromInt, _:byte ) = fun (x:int) -> byte x
static member ($) (FromInt, _:uint16 ) = fun (x:int) -> uint16 x
static member ($) (FromInt, _:char ) = fun (x:int) -> char x
static member ($) (FromInt, _:uint32 ) = fun (x:int) -> uint32 x
static member ($) (FromInt, _:uint64 ) = fun (x:int) -> uint64 x
static member ($) (FromInt, _:unativeint) = fun (x:int) -> unativeint x
static member ($) (FromInt, _:bigint ) = fun (x:int) -> bigint x
static member ($) (FromInt, _:decimal ) = fun (x:int) -> decimal x
static member ($) (FromInt, _:Complex ) = fun (x:int) -> Complex(float x,0.0)
let inline fromInt (a:int) : ^t = (FromInt $ Unchecked.defaultof< ^t>) a
module NumericLiteralG =
let inline FromZero() =LanguagePrimitives.GenericZero
let inline FromOne() = LanguagePrimitives.GenericOne
let inline FromInt32 (i:int) = fromInt i
// This will reduce the number of types inferred, will reduce compile time too.
let inline (+) (a:^t) (b:^t) : ^t = a + b
let inline (-) (a:^t) (b:^t) : ^t = a - b
let inline (*) (a:^t) (b:^t) : ^t = a * b
let inline (/) (a:^t) (b:^t) : ^t = a / b
let inline (~-) (a:^t) : ^t = -a
let inline halfSquare num =
let res = num / 2G
res * res
let solve1 = halfSquare 5I
let solve2 = halfSquare 5.0
let solve3 = halfSquare 5uy
// Define more generic math functions.