DateTime.Today Error
In VS2010 for a VB.NET 4.0 project, the IDE puts a green line under the last line in the following code:
Dim cityLocal As DateTime
cityLocal = externalFunction()
cityLocal.Today()
The suggested code replace is to update 'cityLocal' with 'Date'. The reason is: Access of开发者_开发百科 shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
But it does compile and does work correctly. Is this just a bug in the VS2010?
Today is a shared member, thus should not (but can) be accessed through an instance of DateTime change your code to.
DateTime.Today
Although Visual Studio gives you suggestions to correct the "Error" it is infact a compiler warning, warning you that there is no need for an instance to access the shared member. You'll find that it is not listed as an error in the error list. Which is why it compiles correctly.
The Visual Basic language specification states
9.2.4 Shared Methods
The Shared modifier indicates a method is a shared method. A shared method does not operate on a specific instance of a type and may be invoked directly from a type rather than through a particular instance of a type. It is valid, however, to use an instance to qualify a shared method.
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=01EEE123-F68C-4227-9274-97A13D7CB433:
More information on the warning can be found in the documentation.
http://msdn.microsoft.com/en-us/library/y6t76186.aspx
Date.Today
is a static
(Shared
in VB.NET) property. You are able to use it from an instance because the compiler knows to make the proper call, but it is not the expected usage pattern, which is both unnecessary and undesirable to use directly from an instance.
As a static variable, you should use Date.Today
rather than variable.Today
.
Today is a shared/static member. Normally you would use DateTime.Today
not your instance variable.
http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx
精彩评论