首页 > 代码库 > .NET 4新特性——数组、元组比较
.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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。