나는, 예를 들어,myNullableLong.HasValue와 myNullableLong! = null 사이에 차이가 있습니까?
myNullableLong.HasValue
및
myNullableLong != null
의 차이는 길이가 널 (NULL) ... 또는 그냥 '문법 설탕'입니다 있나요?
나는, 예를 들어,myNullableLong.HasValue와 myNullableLong! = null 사이에 차이가 있습니까?
myNullableLong.HasValue
및
myNullableLong != null
의 차이는 길이가 널 (NULL) ... 또는 그냥 '문법 설탕'입니다 있나요?
구문당 일뿐입니다. 어쨌든 무효 테스트는 실제로 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
당신은 둘 중 어느 것을 '깔끔하게'생각하십니까? –
@Neil : 상황에 따라 다릅니다. 아마도 * 보통 * null 비교를 사용하지만 가끔 'HasValue'가 더 읽기 쉬울 것이라고 생각합니다. –
감사합니다. 나는'HasValue' 비교보다'! = null'을 더 많이보아야한다고 말해야합니다. –
그것은 문법 설탕입니다; Nullable<T>
은 실제로는 struct
이므로 은 실제로는 일 수 없습니다. null
입니다. 컴파일러는 null
(두 번째 예와 같이)과 비교되는 호출을 HasValue
에 대한 호출로 변환합니다. object
에 Nullable<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
http://msdn.microsoft.com/en-us/library/ms228597.aspx를 참조하십시오. –
번호
C# 컴파일러가Nullable<T>
에 대한 지원 내장하고 구조체의 멤버에 대한 호출에
null
을 포함하는 평등 작업을 켜집니다
.
n != null
및 n.HasValue
은 모두 동일한 IL로 컴파일됩니다.
[유사 질문] (http://stackoverflow.com/questions/676078/which-is-preferred-nullable-hasvalue-or-nullable-null) – DOK