问题描述
抛开是否应该对无单位概念(例如角度)使用度量单位,假设我在F#中定义了degree
和radian
单位
Leaving aside whether we should use units of measure for unitless concepts like angles, suppose I have define degree
and radian
units in F#
type [<Measure>] degree =
static member ToRadians (d:float<degree>) : float<radian> = d * (Math.PI * 1.<radian>) / 180.0<degree>
and [<Measure>] radian =
static member ToDegrees (r:float<radian>) : float<degree> = r * 180.0<degree> / (Math.PI * 1.<radian>)
我可以像这样相对容易地使用它们
I can use them relatively easily like
4.0<degree> |> degree.ToRadians
似乎扩展成员会更方便.所以我只能说
It seems like extension members would be even handier. So I could just say
let d = 4.0<degree>
let r = d.ToRadians()
但是我无法以明显的方式定义扩展成员
But I can't define the extension member the obvious way
type float<degree> with
member degrees.ToRadians() = degree.ToRadians(degrees)
...这给我以下错误
... this gets me the following error
error FS0010: Unexpected identifier in type name. Expected infix operator, quote symbol or other token.
在F#中以扩展为单位的扩展成员是否有语法技巧,或者该功能受支持?
Is there a syntactic trick for extension members on units of measure in F#, or is the feature supported?
推荐答案
F#扩展成员与C#扩展成员的不同之处在于,您无法定义构造的泛型类型的扩展.例如,您可以在seq<'t>
上定义扩展名,但不能在seq<int>
上定义扩展名.换句话说,扩展成员实际上就像该类型的成员一样,而不是静态方法.这也适用于度量类型,因此您不能在float<degree>
上定义扩展名,但是可以在float<[<Measure>]'u>
上定义扩展名:
F# extension members are different from C# extension members in that you can't define extensions of constructed generic types. For instance, you can define extensions on seq<'t>
, but not seq<int>
. In other words, extension members really act like members of the type, rather than static methods. This applies to measure types too, so you can't define an extension on float<degree>
, but you can define an extension on float<[<Measure>]'u>
:
type float<[<Measure>]'u> with
member f.Squared() = f * f
[<Measure>]
type m
let area = 2.0<m>.Squared()
但是,我看不出这对您有什么帮助……
However, I don't see how this helps you in your case...
这篇关于如何在F#度量单位上定义扩展成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!