本文介绍了如何使用F#中的度量单位打印结果单位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习如何在F#中使用度量单位,但是我还没有找到这个简单问题的答案.计算后如何打印结果单位.我知道FSI会打印它们,因此应该可以使用它们.

I am beginning to learn how to use units of measure in F# but I haven't found the answer to this simple question yet. How do you print the resultant units after a calculation. I know that FSI prints them so they should be available somehow.

例如:

[<Measure>] type m;;

[<Measure>] type s;;

let d = 10<m>;;
val d : int<m> = 10

let t = 2<s>;;
val t : int<s> = 2

我想做这样的事情:

printfn "Results: %A %A" (d / t) (UOM (d / t));;
"Results: 5 m/s"

预先感谢

推荐答案

不幸的是,这是不可能的.

Unfortunately, this is not possible.

度量单位仅在编译时存在.当您编译程序时,它们会增加(因为.NET没有任何表示类型单位的方法).这意味着在运行时,计算结果仅为float.我认为除了在代码中将单位写为字符串外,别无他法.

Units of measure exist only at compile time. When you compile the program, they will be ereased (because .NET doesn't have any way of representing units for types). This means that at the runtime, the result of your calculation will be just float. I don't think there is any way other than just writing units as string in your code...

前段时间有一个相关的问题.它具有更多详细信息,并说明了为什么无法使用反射获得有关单位的信息.

There was a related question some time ago. It has some more details and also explains why you cannot get information about units using reflection.

这篇关于如何使用F#中的度量单位打印结果单位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 09:43