如何识别重新定义的变量或阴影变量

How to identify redefined variables or shadowed variables

当使用 F# 编译器在同一范围内两次使用同一变量时,没有警告或反馈。例如

let s = "abc"
let s = "def"
printfn "%A" s

结果

def

我看过
Is there a way to have warnings for shadowing values in F# in Visual Studio?

有没有办法通过编译器警告或在编辑器中以可视方式获得有关阴影变量的反馈。如何做到这一点?

首先,在同一范围内隐藏变量不是错误,也不是应该禁用的东西。正如 Joel Mueller 所说,它是 legitimate, useful, and common

MSDN

At any level of scope other than module scope, it is not an error to reuse a value or function name. If you reuse a name, the name declared later shadows the name declared earlier.


Syntax Coloring feature of the Visual Studio extension F# Power Tools 将突出显示当前有效变量并将阴影变量显示为浅灰色。例如

可以从 Visual Studio 菜单安装扩展程序

工具 -> 扩展和更新
对话框打开后
Select Visual Studio 图库
在右上方的搜索框中输入 F# Power Tools
由于我已经安装了它,所以没有显示安装选项。

可以从 Visual Studio 菜单激活该功能

工具 -> 选项 -> F# Power Tools -> 常规 -> 语法着色 -> 灰色未使用的声明

关闭选项:

启用选项:

注意:更改选项后,必须关闭源文件然后重新打开才能使更改生效。 Visual Studio 不需要为此重新启动,但这样做会产生相同的效果。

感谢 Ringil 指出我之前的无效陈述。

源代码注释:

Graying out unused declarations


Currently unused non public types, methods, functions and values declarations are checked. Beware that this feature is only 100% reliable when the code has no type error. This setting is available in General options. It is disabled by default because there might be performance issues on large files.

F# Power Tools features list