参见2个简单的代码示例:
示例1:返回True
class Program{ static voID Main(string[] args) { object o1 = "ABC"; object o2 = "ABC"; Console.Writeline("object1 and object2: {0}",o1.Equals(o2)); }}
示例2:两个语句都返回False
class Program{ static voID Main(string[] args) { Person person1 = new Person("John"); Person person2 = new Person("John"); Console.Writeline("person1 and person2: {0}",person1.Equals(person2)); Console.Writeline("person1 and person2: {0}",((object)person1).Equals((object)person2)); Console.Readline(); }}public class Person{ private string personname; public Person(string name) { this.personname = name; }}解决方法 这里有两种效果:
>字符串实习意味着即使您执行引用相等性检查,您仍然会看到True.你可以像这样修复:
object o1 = new StringBuilder("ABC").ToString();object o2 = new StringBuilder("ABC").ToString();
> System.String overrides the Equals
method比较字符串的内容:
This method performs an ordinal (case-sensitive and culture-insensitive) comparison.
你可以在这里看到不同之处:
object o1 = new StringBuilder("ABC").ToString();object o2 = new StringBuilder("ABC").ToString();Console.Writeline(o1.Equals(o2)); // Prints True due to overrIDingConsole.Writeline(ReferenceEquals(o1,o2)); // Prints False
你的类不会覆盖Equals,所以你得到default implementation in Object
,这是比较引用:
If the current instance is a reference type,the Equals(Object) method tests for reference equality,and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method.
你可以通过重写Equals来合理地解决这个问题:
// It's easIEr to implement equality correctly on sealed classespublic sealed class Person{ private Readonly string personname; public Person(string name) { if (name == null) { throw new ArgumentNullException("name"); } this.personname = name; } public overrIDe bool Equals(object other) { Person person = other as Person; return person != null && person.personname.Equals(personname); } // Must overrIDe GetHashCode at the same time... public overrIDe int GetHashCode() { // Just delegate to the name here - it's the only thing we're // using in the equality check return personname.GetHashCode(); }}
请注意,在Equals实现中,我们可以使用:
return person != null && person.personname == personname;
…因为string也会重载==运算符.但那是另一回事:)
总结以上是内存溢出为你收集整理的c# – 参考类型中的平等全部内容,希望文章能够帮你解决c# – 参考类型中的平等所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)