Option Strict and DefaultValueAttribute
Having just 开发者_StackOverflow社区spent the past several hours trying to work out why my Xml Serialization code was not working. Consider the following:
<DefaultValueAttribute(False)>
Public Property UserName() As String
Why is this allowed regardless of option strict being on (or not)?
Quite simple. The DefaultValueAttribute
has an overload which accepts boolean values so it will work with or without Option Strict
on.
Check this page for more information DefaultValueAttribute Class.
The answer is that VS does not type check default values for VB.NET, regardless of OptionStrict or not.
<DefaultValueAttribute(False)>
is valid because the attribute definition is really a constructor and not a type definition, as such it's type is DefaultValueAttribute
and not a return type of boolean
. Furthermore the .Value
property of the DefaultValueAttribute
is of type Object
and hence it's type cannot be compared either, as such the very existence of DefaultValueAttribute
violates Option Strict On
and hence Option Strict
ignored for the scope of DefaultValue
Attributes.
精彩评论