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

后端 未结 4 950
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:24

    One way this could == null is if you practiced some black magic by overloading the == operator. For example, if someone decides that having a null or empty-string dni is equivalent to a null person:

    public static bool operator ==(Person a, Person b)
    {
        if(String.IsNullOrEmpty(a.dni) && (object)b == null)
            return true;
    
        if(String.IsNullOrEmpty(b.dni) && (object)a == null)
            return true;
    
        return Object.ReferenceEquals(a, b);
    }
    

    Note this is probably a Really Bad Idea.

提交回复
热议问题