资源描述:
《C#-数组(下)——元组.比较》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingInstance1;usingSystem.Collections;namespaceInstance{classProgram{staticvoidMain(string[]args){//Instance1.gram.Divide()//varresult=Instance1.gram.Divide(5,2);//Console.WriteLine("resultofdi
2、vision:{0}//////reminder{1]",result.Item1,result.Item2);//超过八个参数的Tuple类定义,使用模板参数TRest//Instance1.Person()varjanet=newInstance1.Person{FirstName="Janet",LastName="Jackson"};Person[]persons1={newPerson{FirstName="Michael",LastName="Jackson"},janet};Person[]persons2={newPerson{FirstName="Michael",LastN
3、ame="Jacson"},janet};if(persons1!=persons2)Console.WriteLine("notthesameregerence");if((persons1asIStructuralEquatable).Equals(persons2,EqualityComparer.Default))//as强制转换为IStructuralEquatable接口{Console.WriteLine("thesamecontent");}if((persons1asIStructuralEquatable).Equals(persons2,EqualityC
4、omparer.Default)){//EqualityComparer(T)检查T是否实现IEquatable接口并调用IEquatable.Equals()方法,没有继承接口则调用object的Equals()方法Console.WriteLine("thesamecontent");}//对元组执行相同的操作vart1=Tuple.Create(1,"tuple");vart2=Tuple.Create(1,"stephanie");if(t1!=t2)//因为引用两个不同不同对象所以true{Console.WriteLi
5、ne("notthereferencetothetuple");}if(t1.Equals(t2))//因为值一样,所以返回trueConsole.WriteLine("tbesamecontrnt");//使用自定义类给Tuple类的方法传递一个新实例,要调用两次TupleComparer,来检查是否相等//if(t1.Equals(t2,newTupleComparer()))//Console.WriteLine("equalsusingTupleComparer");Console.ReadKey();return;}}}namespaceInstance1{public
6、classgram{publicstaticTupleDivide(intdividend,intdivisor){intresult=dividend/divisor;intreminder=dividend%divisor;returnTuple.Create(result,reminder);}}//元组合并不同类型的对象publicclassPerson:IEquatable{publicintId{get;set;}publicstringFirstName{get;set;}publicstringLastName{get;set
7、;}publicoverridestringToString(){returnString.Format("{0}{1}{2}",Id,FirstName,LastName);}publicoverrideboolEquals(objectobj){if(obj==null)thrownewArgumentNullException("obj");returnEquals(objasPerson)