2011-03-08 2 views

답변

53

구문당 일뿐입니다. 어쨌든 무효 테스트는 실제로 HasValue에 대한 호출로 컴파일됩니다.

샘플 :

public class Test 
{ 
    static void Main() 
    { 
     int? x = 0; 
     bool y = x.HasValue; 
     bool z = x != null; 
    } 
} 

IL :

.method private hidebysig static void Main() cil managed 
{ 
    .entrypoint 
    // Code size  25 (0x19) 
    .maxstack 2 
    .locals init (valuetype [mscorlib]System.Nullable`1<int32> V_0) 
    IL_0000: ldloca.s V_0 
    IL_0002: ldc.i4.0 
    IL_0003: call  instance void valuetype [mscorlib]System.Nullable`1<int32>::.ctor(!0) 
    IL_0008: ldloca.s V_0 
    IL_000a: call  instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue() 
    IL_000f: pop 
    IL_0010: ldloca.s V_0 
    IL_0012: call  instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue() 
    IL_0017: pop 
    IL_0018: ret 
} // end of method Test::Main 
+0

당신은 둘 중 어느 것을 '깔끔하게'생각하십니까? –

+2

@Neil : 상황에 따라 다릅니다. 아마도 * 보통 * null 비교를 사용하지만 가끔 'HasValue'가 더 읽기 쉬울 것이라고 생각합니다. –

+2

감사합니다. 나는'HasValue' 비교보다'! = null'을 더 많이보아야한다고 말해야합니다. –

8

그것은 문법 설탕입니다; Nullable<T>은 실제로는 struct이므로 은 실제로는 일 수 없습니다. null입니다. 컴파일러는 null (두 번째 예와 같이)과 비교되는 호출을 HasValue에 대한 호출로 변환합니다. objectNullable<T> 복싱 비록

주, T 값 중 발생하거나 null (그 값이있는 경우) (그렇지 않는 경우).

I.E.

int? foo = 10; // Nullable<int> with a value of 10 and HasValue = true 
int? bar = null; // Nullable<int> with a value of 0 and HasValue = false 

object fooObj = foo; // boxes the int 10 
object barObj = bar; // boxes null 

Console.WriteLine(fooObj.GetType()) // System.Int32 
Console.WriteLine(barObj.GetType()) // NullReferenceException 
+1

http://msdn.microsoft.com/en-us/library/ms228597.aspx를 참조하십시오. –

3

번호

C# 컴파일러가 Nullable<T>에 대한 지원 내장하고 구조체의 멤버에 대한 호출에 null을 포함하는 평등 작업을 켜집니다

.

n != nulln.HasValue은 모두 동일한 IL로 컴파일됩니다.

관련 문제