F# nameof 运算符不是一流的函数 [英] F# nameof operator not a first-class function

查看:37
本文介绍了F# nameof 运算符不是一流的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目文件中使用带有 preview 的 F# 4.7.

I'm using F# 4.7 with <LangVersion>preview</LangVersion> in my project file.

我有一个这样的类型:

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
  ]

推荐答案

特殊函数 nameof 是一个编译时特性,返回标识符的静态名称.因此,它不能在运行时使用,您的运行时代码将不包含对该函数的任何引用,结果始终是编译时常量.

The special function nameof is a compile time feature, and returns the static name of the identifier. 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.

因此,您不能将其与管道一起使用,也不能用作第一类功能.当你尝试时,你会得到给定的错误.

As a consequence of this, you cannot use it with piping, or as a first 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).

添加这个特殊函数/运算符的主要原因是帮助重命名代码中的操作,或者在像 ArgumentNullException 这样的异常中安全地使用参数的名称.

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.

完整细节在 RFC 中,特别是其他注意事项"部分,其中详细介绍了您的用例:https://github.com/fsharp/fslang-design/blob/master/preview/FS-1003-nameof-operator.md

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

在实现中,就不需要使用 Unchecked.defaultof 进行了长时间的讨论,但我们找不到一个好的方法来做到这一点,而无需对解析器进行大量重写.请注意,该代码不会增加运行时开销,而是已删除.

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. Note that that code doesn't add runtime overhead, it's erased.

这篇关于F# nameof 运算符不是一流的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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