gpt4 book ai didi

.net - F# int.MaxValue 是 "not a valid constant expression,"但 System.Int32.MaxValue 是?

转载 作者:行者123 更新时间:2023-12-02 11:02:08 24 4
gpt4 key购买 nike

TL;DR: F# 编译器在此上下文中将 int 解释为 int operator ,如determined by Eugene Fotinexpanded upon by Gene Belitski 。最好的解决方法是使用 System.Int32.MaxValue 或如下所述的唯一类型别名。

<小时/>

考虑以下记录类型:

type User = {
Username : string
}

我希望用户名的长度至少为三个字符,因此我使用StringLength属性。没有最大长度,所以我将其设置为 int.MaxValue:

type User = {
[<StringLength(int.MaxValue, MinimumLength=3)>]
Username : string
}

这给了我以下错误:

This is not a valid constant expression or custom attribute value.

如果我使用System.Int32,一切都会变得完美:

type User = {
[<StringLength(System.Int32.MaxValue, MinimumLength=3)>]
Username : string
}

如果我别名 int,它也会编译:

type User = {
[<StringLength(num.MaxValue, MinimumLength=3)>]
Username : string
}
and num = int

或者完全限定类型:

type User = {
[<StringLength(Microsoft.FSharp.Core.int.MaxValue, MinimumLength=3)>]
Username : string
}

我检查了 F# 源代码并 int is defined exactly as you would expect :

type int32 = System.Int32
// Then, a few lines later…
type int = int32

发生什么事了?我认为 F# 基元类型在大多数情况下可以与其他类型互换,但我的思维模型似乎缺少一些东西。

最佳答案

这就是 F# 类型推断在不同上下文中的工作原理,不同的语法实体同时具有相同的名称,在 int 的情况下就是这样。可以是以下任意一个:

  • 功能int:'T->int全名Microsoft.FSharp.Core.Operators.int
  • type int = int32全名Microsoft.FSharp.Core.int
  • type int<'Measure> = int全名Microsoft.FSharp.Core.int<_>

演示此工作原理的一种方法是以下场景:如果我们只是输入

int;;

在 FSI 中我们会得到类似的东西

val it : (int -> int) = <fun:it@3>

换句话说,它是一个不能有 MaxValue 的函数与其相关的属性:

> int.MaxValue;;

int.MaxValue;;
----^^^^^^^^

... error FS0039: The field, constructor or member 'MaxValue' is not defined

这同样适用于 int32 ,当在表达式上下文中使用时,FSI 将其推断为另一个带有签名 (int -> int32) 的函数。 .

现在说到

type num = int

在这种情况下int被推断为 System.Int32 的类型名称缩写,所以num也是一个类型缩写,但现在名称歧义不再存在,所以 num.MaxValue完全按照我们的预期推断,给出 FSI

> num.MaxValue;;
val it : int = 2147483647

最后,当您使用Microsoft.FSharp.Core.int时您明确引用类型实体,没有歧义的地方,因此它按预期工作。

返回带有属性参数的用例 - 在本上下文中 int被类型推断视为传递参数值的表达式的一部分,即作为函数,除非您显式或间接设置其他解释。

关于.net - F# int.MaxValue 是 "not a valid constant expression,"但 System.Int32.MaxValue 是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20271205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com