最佳实践:选项推断 [英] Best Practices: Option Infer

查看:28
本文介绍了最佳实践:选项推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您认为在您的项目中使用 Option Infer 的最佳实践是什么?

What do you feel are best practices for the use of Option Infer in your projects?

在 Visual Studio 2008 中,Option Infer 是一个指令,允许编译器通过查看分配给它的内容来推断声明变量的数据类型.

In Visual Studio 2008, Option Infer is a directive that allows the compiler to infer the datatype of a declared variable by looking at what is assigned to it.

这是 VS2008 的一个关键特性,广泛用于 LINQ 语句和查询.但是,开启 Option Infer 可能会给未来的维护程序员带来陷阱.

This is a key feature in VS2008 and is used extensively with LINQ statements and queries. However, turning on Option Infer may create pitfalls for future maintenance programmers.

推荐答案

C#(因此我认为其他 .net 语言)使用的类型推断非常精确(并且非常出色).编译器仅在类型明确且无歧义的情况下才允许该语句.因此,结果并不是真正的精度损失……这只是使开发人员免于多次声明类型.您正在减少代码中的重复.

The type inference used by C# (and thus I presume other .net languages) is very precise (and excellent). The compiler will only allow the statement if the type is clear and unambiguous. Therefore, the outcome is not really a loss in precision ... it is merely that you're saving the developer from stating the type more than once. You're reducing duplication in the code.

(另外,重要的是要意识到结果是仍然是强类型的.编译器在编译时知道变量的确切类型.没有像一个变体.如果你输入 var x = 42; 它只是认为 x 是一个 int 因为你在右边放了一个 int,从而为您节省一些打字和重复).

( Also, it is important to realize that the result is still strongly typed. The compiler knows, at compile time, exactly what type the variable is. There is nothing like a variant involved. If you type var x = 42; it simply figures out that x is an int because you put an int on the right-hand side, thus saving you some typing and duplication).

未来的维护程序员可能不理解它的唯一原因是他们根本不理解类型推断的语言特性.但我认为,期望并要求维护程序员了解语言特性,而不是因为担心未来的程序员不知道它们而避免使用良好的语言特性,这更合理.

The only reason future maintenance programmers might not understand it is if they simply don't understand the language feature of type inference in the first place. But I think it is more sound to expect and require that maintenance programmers know the language features, than it is to avoid good language features out of fear that future programmers won't know them.

我想,如果您知道未来的程序员是初级程序员并且对语言不是很了解,那么您可能会避免一些事情.但这让我想知道您是否应该考虑使用其他语言,甚至像 Access 这样的平台",它是真正的编程"和非程序员可以使用的东西的混合体.

I guess if you're in a situation where you know that future programmers are junior and not very knowledgeable about the language, then maybe you would avoid some things. But that makes me wonder if you should consider some other language, or even a "platform" like Access which is a hybrid of "real programming" and something that a non-programmer can do some things with.

这篇关于最佳实践:选项推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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