简体   繁体   English

F# nameof operator 不是一流的 function

[英]F# nameof operator not a first-class function

I'm using F# 4.7 with <LangVersion>preview</LangVersion> in my project file.我在我的项目文件中使用带有<LangVersion>preview</LangVersion>的 F# 4.7。

I have a type like this:我有这样的类型:

type Record = {
  Name : string
  Description : string
  FieldNotInterestedIn: int
}

I'd like to get the names of certain fields in a type-safe way, but not all of them.我想以类型安全的方式获取某些字段的名称,但不是全部。 I know I can get all the field names using reflection.我知道我可以使用反射获取所有字段名称。

Here's the most concise code I came up with.这是我想出的最简洁的代码。 Can it be any more concise?能不能再简洁点?

let certainFieldNames =
  let r = Unchecked.defaultof<Record>
  
  [
    nameof r.Name
    nameof r.Description
  ]

The special function nameof is a compile time feature, and returns the static name of the identifier.特殊的 function nameof是一个编译时特性,并返回标识符的 static 名称。 As such, it cannot be used at runtime, your runtime code will not contain any references to the function, the result is always a compile time constant.因此,它不能在运行时使用,您的运行时代码不会包含对 function 的任何引用,结果始终是编译时间常数。

As a consequence of this, you cannot use it with piping, or as a first class function.因此,您不能将其与管道一起使用,也不能作为第一个 class function 使用。 When you try it, you'll get the error as given.当你尝试它时,你会得到给定的错误。

The code you wrote is about the most concise, since you seem to want to get the name of these identifiers.您编写的代码是最简洁的,因为您似乎想要获取这些标识符的名称。 There's no syntactic way to do this dynamically (other than with reflection, but that's a whole different approach).没有语法方法可以动态地做到这一点(除了反射,但这是一种完全不同的方法)。

The main reason this special function/operator was added was to help with renaming operations in code, or to safely use the name of a parameter in exceptions like ArgumentNullException .添加此特殊函数/运算符的主要原因是帮助重命名代码中的操作,或者在ArgumentNullException等异常中安全地使用参数名称。

Full details are in the RFC, in particular the section "other considerations", which details your use case: https://github.com/fsharp/fslang-design/blob/master/preview/FS-1003-nameof-operator.md完整的详细信息在 RFC 中,特别是“其他注意事项”部分,其中详细说明了您的用例: https://github.com/fsharp/fslang-design/blob/master/preview/FS-1003-nameof-operator。 MD

In the implementation, a long discussion was held with respect to not requiring the use of Unchecked.defaultof , but we couldn't find a good way of doing that without a significant rewrite of the parser.在实现中,就不需要使用Unchecked.defaultof进行了长时间的讨论,但是如果不对解析器进行重大重写,我们就找不到这样做的好方法。 Note that that code doesn't add runtime overhead, it's erased.请注意,该代码不会增加运行时开销,它会被删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM