我需要将值转换为其他数据类型,因为环境处理米、秒、弧度、度等。我也使用测量单位。我的问题源于对 C# 代码的依赖并需要在我的项目中使用它。
这似乎是一个微不足道的问题,但我一生都无法解决这个问题。如果我可以进去并将单位添加到原始定义中,那不会有问题,但我需要将它们添加到现有类型和现有值中。
这是一个演示 C# 项目。 F# 项目将此作为依赖项。
namespace test
{
public class Polygon
{
public int angle = 3;
public int length = 1;
}
}
这里是 F# 项目,其中包含我在转换和添加测量单位时失败的各种方法。
[<Measure>] type m
open test
let x : int = 1;
// == trying to cast int to float and assign unit-of-measure ==
type a = float<m>
let y:a = a x // The value or constructor 'a' is not defined
let y:a = (a)x // The value or constructor 'a' is not defined
let y:a = upcast (float x) // Type constraint mismatch. The type 'float' is not compatible with type 'a'
// The type 'a' does not have any subtypes and need not be used as the
// target of a static coercion.
let y:a = downcast (float x) // The type 'float' does not have any proper subtypes and cannot be used
// as the source of a type test or runtime coercion.
let y:a = float<m> x // Expected type, not unit-of-measure
let y:a = (float x)<m> // Unexpected token '>' or incomplete expression
let y:a = (float<m>)(float x) // Expected type, not unit-of-measure
// == trying to only assign unit-of-measure ==
type b = int<m>
let y:b = x // This expression was expected to have type 'b' but here has type 'int'
let y:b = x<m> // Unexpected type arguments
let y:b = (x)<m> // Unexpected token '>' or incomplete expression
// == actual usecase ==
let getLength (shape : test.Polygon) : float<m> =
float<m> shape.length // ???
let getSides (shape : test.Polygon) : float =
float shape.angle
let usecase (shape : test.Polygon) =
let fancySide = getLength shape
let fancySides = getSides shape
fancySide + fancySides // Needs to give error
您可以使用
FloatWithMeasure
进行此转换:
let y:a = LanguagePrimitives.FloatWithMeasure x
有关详细信息,请参阅 F# 语言指南:
要将无单位值转换为有单位的值,您可以乘以用适当单位注释的 1 或 1.0 值。但是,为了编写互操作性层,还可以使用一些显式函数将无单位值转换为有单位的值。这些位于 FSharp.Core.LanguagePrimitives 模块中。