加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

.net – F#int.MaxValue是“不是有效的常量表达式”,但System.In

发布时间:2020-12-14 16:31:53 所属栏目:Java 来源:网络整理
导读:TL; DR:F#编译器在本上下文中将int解释为 int operator,如 determined by Eugene Fotin和 expanded upon by Gene Belitski.最佳解决方法是使用System.Int32.MaxValue或唯一类型别名,如下所述. 考虑以下记录类型: type User = { Username : string} 我想要
TL; DR:F#编译器在本上下文中将int解释为 int operator,如 determined by Eugene Fotin和 expanded 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
}

它也编译如果我alias 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可能是以下任何一种:

> function int:’T> int的全名为Microsoft.FSharp.Core.Operators.int
>键入int = int32的全名Microsoft.FSharp.Core.int
> type int&”Measure> =全名为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推断为仅具有signature(int – > int32)的另一个函数.

现在谈到

type num = int

在这个上下文中,int被推断为System.Int32的类型名称缩写,所以num也是一个类型缩写,但是现在名称模糊性没有地方,所以num.MaxValue是我们期望的,我们期望的是在FSI

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

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

返回到你的用例属性参数 – 在这个上下文中,int被类型推断作为表达式的一部分来处理,以提供参数值,即作为函数,除非你明确或间接设置另一个解释.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读