我發現一個有趣的事情,以此爲C#程序:如果你複製我的代碼和運行,一個空指針異常將被拋出「Equals」不能在超載操作函數中調用?
namespace ConsoleApplication1
{
using System;
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public override bool Equals(object comparedStudent)
{
Student stu = comparedStudent as Student;
if (stu == null)
{
return false;
}
return ID.Equals(stu.ID) && Name.Equals(stu.Name);
}
public override int GetHashCode()
{
return ID.GetHashCode()^Name.GetHashCode();
}
/// <summary>
/// Notice that this will cause NullPointException……Why?
/// If I use "return s1.ID==s2.ID && s1.Name==s2.Name", that'd be OK.
/// </summary>
public static bool operator ==(Student s1, Student s2)
{
return s1.Equals(s2);
}
public static bool operator !=(Student s1, Student s2)
{
return !s1.Equals(s2);
}
}
public class Program
{
static void Main(string[] args)
{
Student s1 = new Student();
s1.ID = 1;
s1.Name = "YourName";
Student s2 = new Student();
s2.ID = 1;
s2.Name = "YourName";
//Why there's an exception here (NullPoint exception)
bool isSame = (s1 == s2);
Console.WriteLine(isSame);
}
}
}
。爲什麼? PS:如果我在重載操作符+中使用「return s1.ID == s2.ID & & s1.Name == s2.Name」,那可以。
爲什麼?我正在使用net4.0 VS2015。
如果您通過將調試點放在「bool isSame =(s1 == s2);」你會很快發現它進入「==」重載函數3次,最後,s1和s2都是null!
相反STU的'== null'使用'object.ReferenceEquals(STU,空)' –
@IanMercer:但是,爲什麼運營商函數被調用調試3次?最後,s1 = s2 = null? – xqMogvKW