I was just looking at this answer, which contains the code for Nullable<T>
from .NET Reflector, and I noticed two things:
- An explicit conversion is required when going from
Nullable<T>
to T
.
- The
==
operator is not defined.
Given these two facts, it surprises me that this compiles:
int? value = 10;
Assert.IsTrue(value == 10);
With the code value == 10
, either value
is being magically converted to an int
(hence allowing int
's ==
operator to be used, or the ==
operator is being magically defined for Nullable<int>
. (Or, I presume less likely, Reflector is leaving out some of the code.)
I would expect to have to do one of the following:
Assert.IsTrue((value.Equals(10)); // works because Equals *is* defined
Assert.IsTrue(value.Value == 10); // works because == is defined for int
Assert.IsTrue((int?)value == 10); // works because of the explicit conversion
These of course work, but ==
also works, and that's the part I don't get.
The reason I noticed this and am asking this question is that I'm trying to write a struct that works somewhat similarly to Nullable<T>
. I began with the Reflector code linked above, and just made some very minor modifications. Unfortunately, my CustomNullable<T>
doesn't work the same way. I am not able to do Assert.IsTrue(value == 10)
. I get "Operator ==
cannot be applied to operands of type CustomNullable<int>
and int
".
Now, no matter how minor the modification, I would not expect to be able to do...
CustomNullable<T> value = null;
...because I understand that there is some compiler magic behind Nullable<T>
that allows values to be set to null
even though Nullable<T>
is a struct, but I would expect I should be able to mimic all the other behaviors of Nullable<T>
if my code is written (almost) identically.
Can anyone shed light on how the various operators of Nullable<T>
work when they appear not to be defined?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…