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

后端 未结 4 949
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:20

    Yes, in some cases. The most common case is if you invoke an instance method using a delegate created by reflection and pass a null receiver. This will print "True":

    public class Test
    {
        public void Method()
        {
            Console.WriteLine(this == null);
        }
    }
    
    public class Program
    {
        public static void Main(string[] args)
        {
            object t = new Test();
            var methodInfo = t.GetType().GetMethod("Method");
            var a = (Action)Delegate.CreateDelegate(typeof(Action), null, methodInfo);
            a();
        }
    }
    

    Honestly, though I've never seen someone actually check thisfor null in production code.

提交回复
热议问题