int
例として使用していますが、これは .Net の任意の値型に適用されます
.Net 1 では、以下はコンパイラ例外をスローします。
int i = SomeFunctionThatReturnsInt();
if( i == null ) //compiler exception here
現在(.Net 2または3.5で)その例外はなくなりました。
これがなぜなのか私は知っています:
int? j = null; //nullable int
if( i == j ) //this shouldn't throw an exception
問題は、 becauseint?
が null 可能でありint
、暗黙的に にキャストされるようになったことint?
です。上記の構文はコンパイラの魔法です。本当に私たちはやっています:
Nullable<int> j = null; //nullable int
//compiler is smart enough to do this
if( (Nullable<int>) i == j)
//and not this
if( i == (int) j)
だから今、私i == null
たちが得るとき:
if( (Nullable<int>) i == null )
とにかくC#がこれを計算するためにコンパイラロジックを実行していることを考えると、のような絶対値を扱うときにそれを実行しないほどスマートになれないのはなぜnull
ですか?