Is it possible for 'this' keyword to equal null?

后端 未结 4 948
Happy的楠姐
Happy的楠姐 2021-02-01 15:48

In an example, my professor has implemented Equals as follows:

public class Person {
    private string dni;

    // ...

    public override bool Equals(object          


        
4条回答
  •  盖世英雄少女心
    2021-02-01 16:40

    Yes, it is possible and in fact not entirely unlikely. The C# language gives an excellent guarantee that no method can be called on a null reference to a class object, it generates code that makes a null check at the call site. Which certainly does avoid a lot of head-scratching, a NullReferenceException inside the method can be pretty hard to debug without that check.

    That check is however specific to C#, not all .NET languages implement it. The C++/CLI language doesn't for example. You can see it for yourself by creating a solution with a C++ CLR Console mode project and a C# class library. Add a reference in the CLR project to the C# project.

    C# code:

    using System;
    
    namespace ClassLibrary1 {
        public class Class1 {
            public void NullTest() {
                if (this == null) Console.WriteLine("It's null");
            }
        }
    }
    

    C++/CLI code:

    #include "stdafx.h"
    
    using namespace System;
    
    int main(array ^args) {
        ClassLibrary1::Class1^ obj = nullptr;
        obj->NullTest();
        Console::ReadLine();
        return 0;
    }
    

    Output:

    It's null

    This is not otherwise undefined behavior or illegal in any way. It is not verboten by the CLI spec. And as long as the method doesn't access any instance members then nothing goes wrong. The CLR handles this as well, a NullReferenceException is also generated for pointers that are not null. Like it will be when NullTest() accesses a field that isn't the first field in the class.

提交回复
热议问题