为什么对未使用的let绑定没有警告? [英] Why no warning for unused let bindings?

查看:72
本文介绍了为什么对未使用的let绑定没有警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#警告未使用的变量,它们是编译时常量:

C# warns for unused variables that are compile-time constants:

static void Main(string[] args)
{
    var unused = "hey"; //CS0219 The variable 'unused' is assigned but its value is never used
    Console.WriteLine("Hello World!");
}

但是F#编译器没有,即使编辑器现在可以选择它了:

But the F# compiler does not, even though the editor now does pick it up:

如果它不仅涵盖编译时常量,而且涵盖所有let绑定,那么这将在生产中捕获到由琐碎错误引起的真正错误,例如

If it covered not just compile-time constants but all let bindings, this would have caught a real bug in production caused by a trivial mistake, something like

let callApiXyz connectionInfo = async {
    let fullUrl = sprintf "%s..." connectionInfo.Url
    ...
    let! result = httpGet connectionInfo // fail, didn't use the modified url
    // Should have been:
    // let! result = httpGet { connectionInfo with Url = fullUrl }
    ...
}

除了功能不是免费的"功能之外,是否有其他理由不使用此功能?我认为,在功能优先的语言中,与C#相比,在表达式倾向于没有副作用的情况下,这应该更重要.

Is there any reason not to have this (other than "features are not free")? I feel this should be more important in a functional-first language where expressions tend not to have side-effects, than in C#.

推荐答案

您可以通过warnon编译器选项为未使用的绑定启用警告.如果您想严格一点,甚至可以使用warnaserror+将其变成错误.

You can enable warning for unused bindings via the warnon compiler option. If you want to be strict, you can even use warnaserror+ to turn it into an error.

警告编号为1182,默认情况下已关闭,如编译器选项页面.

The warning number is 1182 and it is turned off by default as documented in the compiler options page in the F# documentation.

fsc --warnaserror+:1182 --warnon:1182 Program.fs

如何执行此操作将取决于您的编辑器.在Visual Studio中,可以通过在项目属性中指定其他标志"和将警告作为错误处理"来实现.

How to do this will depend on your editor. In Visual Studio, you can do this by specifying "Other flags" and "Treat warnings as errors" in project properties.

这篇关于为什么对未使用的let绑定没有警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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