KeyValuePair Is Nothing
How can we verify (.NET 2) if a KeyValuePair
has a value assigned or not?
Dim pair as KeyValuePair(Of A, B) = Nothing
if pair.??? Th开发者_JS百科en Return
As is it a structure, it can't be verified with pair Is Nothing
.
Point structure, by eg. has a p.IsEmpty
verification.
Rather than using the "normal" type here - which means you can't detect the difference between a value with the default values of A
and B
as the key and value, you should use a Nullable(Of KeyValuePair(Of A, B))
.
Effectively you're asking exactly the same question as asking whether an Integer
variable has a value, where setting it to Nothing
would give it a value of 0. How can you tell the difference between that 0 and a "real" 0? You can't - which is why Nullable(Of T)
exists in the first place. The exact same logic applies to KeyValuePair
.
Instead of a nullable type, you can compare it to an empty KeyValuePair:
If pair.Equals(New KeyValuePair(Of A, B)) Then Return
See the C# answer: https://stackoverflow.com/a/1641405/151325
This is what the Nullable(Of T)
type is for. Prior to the introduction of generics in .NET 2.0 (which made this type possible), any value type that wished to expose a semantic "empty" value had to do so on its own. This was usually presented by the structure using a "reserved value" to represent "empty", as you see with Point
, where any Point
at (0, 0)
is considered to be "empty". There is no way to distinguish between a Point
that is empty and a Point
that represents the origin. Other ways were contrived to represent emtpy values by using a boolean flag, but the way that these types were used was unintuitive (in that the consuming code still had a value in the variable).
Rather than force every value type that wished to support the concept of an empty or null value, the Nullable(Of T)
type was introduced. This essentially took the latter (i.e. boolean flag) concept and made it available for each and every value type, both system and user-defined. It also allows comparisons between a Nullable(Of T)
and Nothing
(null
in C#) to check for the presence of a value.
One thing that should be made clear, however, is that (as a value type itself), the Nullable(Of T)
structure is never actually a null reference; the ability to compare it against Nothing
is purely a language feature that's present both in VB.NET and C#. Under the covers, all such comparisons are actually checking the HasValue
property on the structure. Additionally, accessing the Value
property of the structure throws an exception if HasValue
is false.
This question is very old, but for a basic solution:
Dim pair as New KeyValuePair(Of A, B)(Nothing, Nothing)
'...'
'<some code that may or may not set pair to KeyValuePair(Of A, B)(Something, Something)>'
'...'
if pair.Key = Nothing Then Return ' some code did not fire
In this case either A
or B
would need to be compatible with = Nothing
or Is Nothing
.
精彩评论