F#:度量单位可以在运行时动态绑定吗? [英] F#: Can units of measure be bound dynamically at runtime?

查看:86
本文介绍了F#:度量单位可以在运行时动态绑定吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对F#还是很陌生,对计量单位"功能很感兴趣,并对它的正常工作方式有一个大概的了解,但是想知道是否有可能将度量绑定到我们不知道的值上措施将一直执行到代码执行完毕?

I'm very new to F# and am intrigued by the Units of Measure functionality and have a rough idea of how it works normally, but would like to know if it's possible to bind measures to values where we don't know what the measure will be until the code is executing?

我正在看的实际示例是将浮点数绑定为货币值,从数据库查询中推断出度量单位.

The practical example I'm looking at is binding floats as currency values where the unit of measure is inferred from a database lookup.

让我们假设每种货币(美元,欧元,澳元等)的度量标准均已宣布:

Let's assume that the measures for each currency (USD, EUR, AUD, etc) are declared normally:

[<Measure>] USD
[<Measure>] EUR
[<Measure>] AUD
...

首先,您需要一种从标识符获取度量类型的方法,理想情况下是度量名称本身,因为货币代码最有可能以3个字符的字符串形式存储和检索(类似于Enum.Parse()).

First you would need a way to obtain a measure's type from an identifier, ideally the measure name itself as the currency code is most likely stored and retrieved as a 3-character string (similar to Enum.Parse()).

然后,您需要一种将float值绑定到上一步中创建的类型的方法.

Then you would need a way of binding a float value to the type created in the previous step.

这是可能的,还是有另一种方法可以达到相同的结果?

Is this possible, or is there another way to achieve the same outcome?

推荐答案

这是不可能的,因为F#度量单位已删除(它们仅在编译时存在).

This isn't possible, since F# units-of-measure are erased (they only exist at compile-time).

您可以使用运行时实现编写一个库(我没有考虑过设计的外观).但是您可能会丢失静态检查.

You could author a library with a runtime implementation (I haven't thought about what a design would look like). But you probably lose the static checking.

我认为可能更好的策略可能是隔离边界,并在边界点(您从数据库读取并推断单位类型的位置)以某种方式将正确的类型放入类型系统中,但取决于代码的方式结构化以及您正在做什么,这可能或不可能/容易...

I think possibly a better strategy may be to isolate the boundary, and at the boundary point (where you read from the database and infer the unit types) somehow get the right types into the type system, but depending on how the code is structured and what exactly you're doing, that may or may not be possible/easy...

这篇关于F#:度量单位可以在运行时动态绑定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆