What is the best way to mix VB.NET's Option St

2019-01-20 08:08发布

问题:

In a related question, my team is about to (hopefully) start using LINQ, and I'd like to take advantage of anonymous types. What is the best way to mix VB.NET's Option Strict (which we've been using through the life of the project) and the new Option Infer directives?

回答1:

Option Strict and Option Infer do not conflict, so I see no harm in having both on.

As a style guide, I prefer to put Option Strict, Explicit, and Infer at the top of each class file - this prevents differences in project or IDE settings from causing issues, and makes it clear what settings are used.



回答2:

Option Strict can be used without Option Infer, but Option Infer should not be used without Option Strict as that can lead to a difference in the resulting IL.

Consider this line of code:

txtBox.Text = If(str=“”, Nothing, CDate(str))

With Option Strict Off and Option Infer Off, that is the equvalent of:

txtBox.Text = CStr(If(str=“”, Nothing, CType(CDate(str), Object)))

If str=“” then txtBox.Text is set to Nothing/empty string.

With Option Infer On but Option Strict Off that becomes:

txtBox.Text = Cstr(If(str=“”, CDate(Nothing), CType(CDate(str), Object)))

And CDate(Nothing) = Date.MinValue and so txtBox.Text = “01/01/0001”

Option Strict can only make your code not compile, Option Infer can change its meaning. That is not to say that Infer can’t be a good thing, in general it is, but there are a few caveats that you need to be aware of.

The original code could be written as:

 txtBox.Text = Cstr(If(str=“”, Nothing, CDate(str)))

In which case Option Strict won’t save you if you turn on Infer, but in a code base without Strict the original version is more likely.