class Person {
private string _name; //姓名.
private string _id; public string Id {
get { return _id; }
set { _id = value; }
}
public string Name {
get { return _name; }
set { _name = value; }
} public Person(string name, string id) {
this._id = id;
this._name = name;
} //override the "==" operator.
//It does not need the implicit(For it just Compare Two stuff rather than Conversion).
public static bool operator ==(Person p1, Person p2) {
if(p1 == null || p2 == null)
throw new NullReferenceException("Person is Null!");
return (p1.Name == p2.Name && p1.Id == p2.Id);
} public static bool operator !=(Person p1, Person p2) {
return !(p1 == p2);
} //Use the tools to override.
public override bool Equals(object obj) {
return base.Equals(obj);
} //Use the tools to override.
public override int GetHashCode() {
return base.GetHashCode();
}
}Call the above code in the Main:
class Program {
static void Main(string[] args) {
Person p1 = new Person("J","jj");
Person p2 = new Person("K", "kk");
Console.WriteLine("p1 == p2" + (p1 == p2));
Console.WriteLine("Use the Object Equals method : " + p1.Equals(p2));
Console.ReadKey();
}
}请问为什么报这样的异常哈?
在比较"=="的时候:
Cannot evaluate expression because the current thread is in a stack overflow state
private string _name; //姓名.
private string _id; public string Id {
get { return _id; }
set { _id = value; }
}
public string Name {
get { return _name; }
set { _name = value; }
} public Person(string name, string id) {
this._id = id;
this._name = name;
} //override the "==" operator.
//It does not need the implicit(For it just Compare Two stuff rather than Conversion).
public static bool operator ==(Person p1, Person p2) {
if(p1 == null || p2 == null)
throw new NullReferenceException("Person is Null!");
return (p1.Name == p2.Name && p1.Id == p2.Id);
} public static bool operator !=(Person p1, Person p2) {
return !(p1 == p2);
} //Use the tools to override.
public override bool Equals(object obj) {
return base.Equals(obj);
} //Use the tools to override.
public override int GetHashCode() {
return base.GetHashCode();
}
}Call the above code in the Main:
class Program {
static void Main(string[] args) {
Person p1 = new Person("J","jj");
Person p2 = new Person("K", "kk");
Console.WriteLine("p1 == p2" + (p1 == p2));
Console.WriteLine("Use the Object Equals method : " + p1.Equals(p2));
Console.ReadKey();
}
}请问为什么报这样的异常哈?
在比较"=="的时候:
Cannot evaluate expression because the current thread is in a stack overflow state
//if(p1 == null || p2 == null) //Can not use "==" operator itself, it will be called recursive.
if(ReferenceEquals(p1, p2))
throw new NullReferenceException("Person is Null!");
return (p1.Name == p2.Name && p1.Id == p2.Id);
}这样修改就好了....