C#編程(十七)----------Object類


Object

它是.NET Framework 中所有類的最終基類;它是類型層次結構的根。也就是說所有的類都擁有object類的方法,並能重寫,調用.

object的構造函數:public Object().

直接使用new object()可以用來創建對象;如果非Object類型,則在該類型的構造函數被調用時,該函數自動被調用.

object類中的方法:

ToString()方法:快速獲取對象的字符串表示的最便捷的方式.

案例:int i=99;string str=i.ToString();

另一個案例:

class Program

    {

        enum Colors

        {

            Red,

            Green,

            Yellow

        }

        static void Main(string[] args)

        {

            Colors color = Colors.Green;

            string str = color.ToString();

        }                

    }

 

Object.ToString()聲明為虛方法,在這些例子中,實現該方法的代碼都是為C#預定義數據類型重寫過的代碼,以返回這些類型的正確字符串表示.Colors枚舉是一個預定義的數據類型,實際上實現一個派生自System.Enum的結構,System.Enum有一個相當智能的ToString()重寫方法,它處理用戶定義的所有枚舉.

如果不在自己定義的類中重寫ToString(),該類將只繼承System.Object的實現方法----它顯示類的名稱.如果希望ToString()返回一個字符串,其中包含類中對象的值信息,就需要重寫它.例如:

class Program

    {       

        static void Main(string[] args)

        {

            Money cash1 = new Money();

            cash1.Amount = 40M;

            Console.WriteLine(cash1.ToString());

            Console.ReadKey();

        }                

    }

    public class Money

    {

        private decimal amount;

        public decimal Amount

        {

            get

            {

                return amount;

            }

            set 

            {

                amount = value;

            }

        }

        public override string ToString()

        {

            return "$"+Amount.ToString();//這里如果不這么寫,寫成base.ToString()會咋樣?如果只寫ToString()會咋樣.

        }

    }

 

 

Equals方法:確定指定的Object是否相等於當前的Object.   Equals默認實現支持引用相等性(德育引用類型)和按位相等性(對於值類型).引用相等性是指進行比較的多個對象引用所引用的是同一個對象.按位相等性是指進行比較的多個對象具有相同的二進制表示形式.

此方法可由派生類重寫.例如,如果兩個對象表示相同的值,則許多基數據類型返回true;否則返回false.

此方法僅比較級元素和對象.若要比較復雜的結構(如對象數組),必須重寫該方法.

案例:

public class Sample {
    void Method() {
    Object Obj1 = new Object();
    Object Obj2 = new Object();
    Console.WriteLine(Obj1.Equals(Obj2)); //===> false
    Obj2 = Obj1;
    Console.WriteLine(Obj1.Equals(Obj2)); //===> true
    }
}

 

GetHashCode方法:用作特定的哈希函數.生成一個與對象的值相對應的數字以支持哈希表的使用。

class Program

    {       

        static void Main(string[] args)

        {

            Hashtable ht = new Hashtable();

            Class3 cc = new Class3(2, 3);

            Class3 cc2 = new Class3(1, 4);

            Class3 cc3 = new Class3(3, 3);

            ht.Add(cc, "test1");

            ht.Add(cc2, "test2");

            ht.Add(cc3, "test3");

            //cc.x = 5;   

            foreach (var item in ht.Keys)

            {

                Console.WriteLine(item.ToString());

                Console.WriteLine(ht[item]);

            }

            Console.Read(); 

        }                

    }

    class Class3

    {

        public int x;

        int y;

        public Class3(int x, int y)

        {

            this.x = x;

            this.y = y;

        }

        public override int GetHashCode()

        {

            Console.WriteLine("判斷hashcode");

            return x + y;

        }

        public override bool Equals(object obj)

        {

            Console.WriteLine("判斷equals");

            return base.Equals(obj);

        }

        public override string ToString()

        {

            return x.ToString() + y.ToString();

        }

    }  

輸出結果為:

判斷hashcode

判斷hashcode

判斷equals

判斷hashcode

33

判斷hashcode

test3

14

判斷hashcode

test2

23

判斷hashcode

判斷equals

test1

分析:

當向Hashtable里插入cc時,這時候哈希表是空的,所以只需要判斷hashcode就行了;

cc2插入哈希表時,判斷哈希碼,由於已經有了一個相同的哈希碼的項,所以這時候需要判斷它倆是不是相同的對象,不相同再插入哈希表。

輸出的時候,

注意cc2那一項判斷了兩次Equals,這是由於按照哈希碼查找到兩個項,再通過key的判斷取出這項的值(key是按照插入的先后順序排列,對比的時候也是從前向后)。

從上面的討論可以看出,哈希碼只有在作為集合索引的時候才起作用,平時根本用不上這個功能,GetHashCode方法其實不用放在Object里面,而是可以單獨放在一個接口里面

 

 

 

Finalize方法

幾乎可以完全肯定地說,對於大多數C++編程人員而言,C#C++最大的不同之處就在於碎片收集。這也意味着編程人員再也無需擔心內存泄露和確保刪除所有沒有用的指針。但我們再也無法精確地控制殺死無用的對象這個過程。事實上,在C#中沒有明確的destructor

如果使用非可管理性資源,在不使用這些資源后,必須明確地釋放它。對資源的隱性控制是由Finalize方法(也被稱為Finalize)提供的,當對象被銷毀時,它就會被碎片收集程序調用收回對象所占用的資源。

Finalize應該只釋放被銷毀對象占用的非可管理性資源,而不應牽涉到其他對象。如果在程序中只使用了可管理性資源,那就無需也不應當C#執行Finalize方法,只有在非可管理性資源的處理中才會用到Finalize方法。由於Finalize需要占用一定的資源,因此應當只在需要它的方法中執行Finalize

直接調用一個對象的Finalize方法是絕對不允許的(除非是在子類的Finalize中調用基礎類的Finalize。),碎片收集程序會自動地調用Finalize.接近C++風格的析構函數,在飲用對象作為垃圾被回收以傾力資源的時候調用它.Finalize方法的Object實現方式實際上什么也沒有做,因而被垃圾收集器忽略.如果對象擁有對未托管資源的引用,則在該對象被刪除時,就需要刪除這些引用,此時一般重寫Finalize().垃圾收集器不能直接傷處這些對未托管資源的引用,因為它只負責托管的資源,於是它只能依賴用戶提供的Finalize()

 

最后:

using System;// The Point class is derived from System.Object.class Point {    public int x, y;     public Point(int x, int y)     {        this.x = x;        this.y = y;    }     public override bool Equals(object obj)     {        // If this and obj do not refer to the same type, then they are not equal.        if (obj.GetType() != this.GetType()) return false;         // Return true if  x and y fields match.        Point other = (Point) obj;        return (this.x == other.x) && (this.y == other.y);    }     // Return the XOR of the x and y fields.    public override int GetHashCode()     {        return x ^ y;    }     // Return the point's value as a string.    public override String ToString()     {        return String.Format("({0}, {1})", x, y);    }     // Return a copy of this point object by making a simple field copy.    public Point Copy()     {        return (Point) this.MemberwiseClone();    }}public sealed class App {    static void Main()     {        // Construct a Point object.        Point p1 = new Point(1,2);         // Make another Point object that is a copy of the first.        Point p2 = p1.Copy();         // Make another variable that references the first Point object.        Point p3 = p1;         // The line below displays false because p1 and p2 refer to two different objects.        Console.WriteLine(Object.ReferenceEquals(p1, p2));         // The line below displays true because p1 and p2 refer to two different objects that have the same value.        Console.WriteLine(Object.Equals(p1, p2));         // The line below displays true because p1 and p3 refer to one object.        Console.WriteLine(Object.ReferenceEquals(p1, p3));         // The line below displays: p1's value is: (1, 2)        Console.WriteLine("p1's value is: {0}", p1.ToString());    }}// This code example produces the following output://// False// True// True// p1's value is: (1, 2)//

 

名稱

說明

Equals(Object)

確定指定的對象是否等於當前對象

Equals(Object,Object)

確定指定的對象實例是否被視為相等

Finalize

允許對象在”垃圾回收”回收之前常識釋放資源並執行其他清理操作

GetHashCode

作為默認哈希函數

GetType

獲取當前實例的Type

MemberwiseClone

創建當前Object的淺表副本

ReferenceEquals

確定指定的Object實例是否是相同的實例

ToString

返回當前對象的字符串


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM