왜 이것을 확인하십시오! = null?

lottogame 2020. 10. 30. 07:38

왜 이것을 확인하십시오! = null?

가끔은 .NET 코드를 살펴보고이면에서 구현되는 방식을 확인하는 데 시간을 보내고 싶습니다. 나는 String.EqualsReflector를 통해 방법 을 보는 동안이 보석을 우연히 발견했습니다 .


[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public override bool Equals(object obj)
    string strB = obj as string;
    if ((strB == null) && (this != null))
        return false;
    return EqualsHelper(this, strB);


.method public hidebysig virtual instance bool Equals(object obj) cil managed
    .custom instance void System.Runtime.ConstrainedExecution.ReliabilityContractAttribute::.ctor(valuetype System.Runtime.ConstrainedExecution.Consistency, valuetype System.Runtime.ConstrainedExecution.Cer) = { int32(3) int32(1) }
    .maxstack 2
    .locals init (
        [0] string str)
    L_0000: ldarg.1 
    L_0001: isinst string
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: brtrue.s L_000f
    L_000a: ldarg.0 
    L_000b: brfalse.s L_000f
    L_000d: ldc.i4.0 
    L_000e: ret 
    L_000f: ldarg.0 
    L_0010: ldloc.0 
    L_0011: call bool System.String::EqualsHelper(string, string)
    L_0016: ret 

확인하는 추론 무엇 this에 대해는 null? 나는 목적이 있다고 가정해야한다. 그렇지 않으면 이것은 아마도 지금 쯤 잡혀서 제거되었을 것이다.

.NET 3.5 구현을보고 있다고 가정합니까? .NET 4 구현이 약간 다르다고 생각합니다.

그러나 이것은 null 참조에서 가상 인스턴스가 아닌 메서드도 호출 할 수 있기 때문 입니다. IL에서 가능합니다. 을 호출하는 IL을 생성 할 수 있는지 살펴 보겠습니다 null.Equals(null).

편집 : 좋아, 여기에 몇 가지 흥미로운 코드가 있습니다.

.method private hidebysig static void  Main() cil managed
  // Code size       17 (0x11)
  .maxstack  2
  .locals init (string V_0)
  IL_0000:  nop
  IL_0001:  ldnull
  IL_0002:  stloc.0
  IL_0003:  ldloc.0
  IL_0004:  ldnull
  IL_0005:  call instance bool [mscorlib]System.String::Equals(string)
  IL_000a:  call void [mscorlib]System.Console::WriteLine(bool)
  IL_000f:  nop
  IL_0010:  ret
} // end of method Test::Main

다음 C # 코드를 컴파일하여 얻었습니다.

using System;

class Test
    static void Main()
        string x = null;


...로 분해 ildasm하고 편집합니다. 이 줄을 참고하십시오.

IL_0005:  call instance bool [mscorlib]System.String::Equals(string)

원래 callvirtcall.

그렇다면 재 조립하면 어떻게 될까요? .NET 4.0을 사용하면 다음과 같은 결과를 얻을 수 있습니다.

Unhandled Exception: System.NullReferenceException: Object
reference not set to an instance of an object.
    at Test.Main()

흠. .NET 2.0은 어떻습니까?

Unhandled Exception: System.NullReferenceException: Object reference 
not set to an instance of an object.
   at System.String.EqualsHelper(String strA, String strB)
   at Test.Main()

이제 더 흥미 롭습니다. 우리는 EqualsHelper일반적으로 예상하지 못했던.

문자열이 충분합니다. 참조 평등을 직접 구현하고 null.Equals(null)true를 반환 할 수 있는지 살펴 보겠습니다 .

using System;

class Test
    static void Main()
        Test x = null;

    public override int GetHashCode()
        return base.GetHashCode();

    public override bool Equals(object other)
        return other == this;

동일 이전과 절차 - 분해, 변경 callvirtcall다시 조립하고, 인쇄보고 true...

Note that although another answers references this C++ question, we're being even more devious here... because we're calling a virtual method non-virtually. Normally even the C++/CLI compiler will use callvirt for a virtual method. In other words, I think in this particular case, the only way for this to be null is to write the IL by hand.

EDIT: I've just noticed something... I wasn't actually calling the right method in either of our little sample programs. Here's the call in the first case:

IL_0005:  call instance bool [mscorlib]System.String::Equals(string)

here's the call in the second:

IL_0005:  call instance bool [mscorlib]System.Object::Equals(object)

In the first case, I meant to call System.String::Equals(object), and in the second, I meant to call Test::Equals(object). From this we can see three things:

  • You need to be careful with overloading.
  • The C# compiler emits calls to the declarer of the virtual method - not the most specific override of the virtual method. IIRC, VB works the opposite way
  • object.Equals(object) is happy to compare a null "this" reference

If you add a bit of console output to the C# override, you can see the difference - it won't be called unless you change the IL to call it explicitly, like this:

IL_0005:  call   instance bool Test::Equals(object)

So, there we are. Fun and abuse of instance methods on null references.

If you've made it this far, you might also like to look at my blog post about how value types can declare parameterless constructors... in IL.

The reason why is that it is indeed possible for this to be null. There are 2 IL op codes which can be used to invoke a function: call and callvirt. The callvirt function causes the CLR to perform a null check when invoking the method. The call instruction does not and hence allows for a method to be entered with this being null.

Sound scary? Indeed it is a bit. However most compilers ensure this doesn't ever happen. The .call instruction is only ever outputted when null is not a possibility (I'm pretty sure that C# always uses callvirt).

This isn't true for all languages though and for reasons I don't exactly know the BCL team chose to further harden the System.String class in this instance.

Another case where this can popup is in reverse pinvoke calls.

The short answer is that languages like C# force you to create an instance of this class before calling the method, but the Framework itself does not. There are two¹ different ways in CIL to call a function: call and callvirt.... Generally speaking, C# will always emit callvirt, which requires this to not be null. But other languages (C++/CLI comes to mind) could emit call, which doesn't have that expectation.

(¹okay, it's more like five if you count calli, newobj etc, but let's keep it simple)

The source code has this comment:

this is necessary to guard against reverse-pinvokes and other callers who do not use the callvirt instruction

Let's see... this is the first string you're comparing. obj is the second object. So it looks like it's an optimization of sorts. It's first casting obj to a string type. And if that fails, then strB is null. And if strB is null while this isn't, then they're definitely not equal and the EqualsHelper function can be skipped.

That will save a function call. Beyond that, perhaps a better understanding of the EqualsHelper function might shed some light on why this optimization is needed.


Ah, so the EqualsHelper function is accepting a (string, string) as parameters. If strB is null, then that essentially means that it was either a null object to begin with, or it couldn't successfully be cast into a string. If the reason for strB being null is that the object was a different type that couldn't be converted to a string then you wouldn't want to call EqualsHelper with essentially two null values (that'll return true). The Equals function should return false in this case. So this if statement is more than an optimization, it actually ensures proper functionality as well.

If the argument (obj) does not cast to a string then strB will be null and the result should be false. Example:

    int[] list = {1,2,3};
    Console.WriteLine("a string".Equals(list));

writes false.

Remember that string.Equals() method is called for any argument type, not only for other strings.

참고URL :