C#編程(三十七)----------結構比較

來源:互聯網
上載者:User

標籤:三十七   eric   ble   over   obj   rom   zhang   sam   write   

結構比較

數組和元組都實現介面IStructuralEquatable和IStructuralComparable.這兩個介面不僅可以比較引用,還可以比較內容.這些介面都是顯示實現的,所以在使用時需要把數組和元組強制轉換為這個介面.IStructuralEquatable介面用於比較兩個元組或數組是否有相同的內容,IStructuralComparable介面用於給元組或數組排序.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace 結構比較

{

    class Program

    {

        static void Main(string[] args)

        {

           //建立兩個Person項的數組.

            //比較子!=返回true

            //因為這其實是兩個變數p1和p2引用的兩個不同數組.

            //因為array類沒有重寫帶一個參數的Equals()放大,所以用"=="運算子

            //比較引用會得到相同的結構,即這兩個變數不相同

            Person zhangsan = new Person { FirstName = "zhang", LastName = "san" };

            Person[] p1 = {

                              new Person

                                {

                                    FirstName="lisi"

                                } ,

            zhangsan

                          };

            Person[] p2 = {

                              new Person

                                {

                                    FirstName="lisi"

                                } ,

            zhangsan

                          };

            if (p1!=p2)

            {

                Console.WriteLine("not the same reference"); ;

            }

            Console.ReadKey();

        }

    }

    public class Person : IEquatable<Person>

    {

        public int ID { get; set; }

        public string FirstName { set; get; }

        public string LastName { set; get; }

 

        public override string ToString()

        {

            return string.Format("{0},{1}{2}", ID, FirstName, LastName); ;

        }

        public override bool Equals(object obj)

        {

            if (obj == null)

            {

                throw new ArgumentNullException("obj");

            }

            return Equals(obj as Person);

        }

        public override int GetHashCode()

        {

            return ID.GetHashCode();

        }

        public bool Equals(Person other)

        {

            if (other == null)

            {

                throw new ArgumentNullException("other");

            }

            return this.ID == other.ID && this.FirstName == other.FirstName && this.LastName == other.LastName;

        }

    }

}

 

使用實現IEquatable介面的Person類.IEquatable介面定義了一個強型別化的Equals()方法,用來比較FirstName和LastName屬性的值.

 

下面看看如何對元組執行相同的操作.這裡建立了兩個內容相同的元組執行個體:

var t1 = Tuple.Create<string, int>("zhangsan", 19);

            var t2 = Tuple.Create<string, int>("zhangsan", 19);

            //因為t1和t2引用了兩個不同的對象,所以比較子"!="返回true

            if (t1 != t2)

            {

                Console.WriteLine("not the same reference to the tuple");

            }

            //這會調用object.equals()方法比較元組的每一項,每一項都返回true

            if (t1.Equals(t2))

            {

                Console.WriteLine("the same reference to the tuple");

            }

Tuple<>類提供了兩個Equals()方法:一個重寫了object基類中的Equals()方法,並把object作為參數,第二個由IStructyralEqualityComparer介面定義,並把object和IequalityComparer作為參數.

 

還可以使用類TupleCOmparer建立一個自訂的UequalityComparer,這個類實現了IEqualityComparer介面的兩個方法Equals()和GetHashCode():

public class TupleComparer : IEqualityComparer

    {

        public bool Equals(object x, object y)

        {

            return x.Equals(y);

        }

 

        public int GetHashCode(object obj)

        {

            return obj.GetHashCode();

        }

}

實現IEqualityCOmparer介面的Equals()方法需要new修飾符或者隱式實現的介面,因為基類object也定義了帶兩個參數的靜態Equals()方法.

 

使用TupleComparer,給Tuple<T1,T2>類的Equals()方法傳遞一個新執行個體.Tuple類的Equals(0方法為要比較的每一項調用TupleComparer的Equals()方法.所以,對於Tuple<T1,T2>類,要調用兩次TupleCOmparer,以檢查所有項是否相等.

C#編程(三十七)----------結構比較

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.