.NET 4新特性——数组、元组比较
==============================================数组自定义比较
------------------------------------------------------------Person.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace ConsoleApplication4 { public class Person:IEquatable<Person>//继承IEquatable泛型接口 { public int Id { get; set; }//属性id,没什么实际意义 public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() { return string.Format("FirstName:{0},LastName:{1}", FirstName, LastName); } public override bool Equals(object obj) { if (obj == null) throw new ArgumentException("error"); return Equals(obj as Person); } public override int GetHashCode()//伴随着 重写的Equals { return Id.GetHashCode(); } public bool Equals(Person other)//重要 { return this.FirstName == other.FirstName;//自定义要比对的值(只比对FirstName) } } }
------------------------------------------------------------主程序
Person p1 = new Person { FirstName = "曹操", LastName = "程昱" }; Person p2 = new Person { FirstName = "曹操", LastName = "荀攸" }; Person p3 = new Person { FirstName = "曹操", LastName = "关羽" }; Person p4 = new Person { FirstName = "刘备", LastName = "关羽" }; Person[] ps1 = { p1, p2 }; Person[] ps2 = { p1, p3 }; Person[] ps3 = { p3, p4 }; // 把数组强制装换成IStructuralEquatable接口 Console.WriteLine((ps1 as IStructuralEquatable).Equals(ps2, EqualityComparer<Person>.Default));//True Console.WriteLine((ps2 as IStructuralEquatable).Equals(ps3, EqualityComparer<Person>.Default));//False Console.ReadKey();
==============================================元组比较
var tuple1 = Tuple.Create<int, int>(1, 2); var tuple2 = Tuple.Create<int, int>(1, 2); Console.WriteLine(tuple1.Equals(tuple2));//True Console.WriteLine(tuple1==tuple2);//False Console.ReadKey();
本文出自 “程序猿的家” 博客,请务必保留此出处http://962410314.blog.51cto.com/7563109/1531758
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。