一、簡介
Object這個類型,相信everyone都不陌生,這個是CLR定義的最基礎的類型,俗稱"上帝類"。CLR(運行時)要求所有類型,不管是系統定義的類型還是自定義的類型,都必須從Object派生,所以以下代碼從本質上是一樣的,代碼如下:
/// <summary> /// 隱式派生自Object /// </summary> class Worker { } /// <summary> /// 顯式派生自Object /// </summary> class Worker : System.Object { }
因為CLR會要求所有的類型都派生自Object,所以自定義類就算沒有顯示繼承Object類,CLR還是會讓自定義類默認繼承Object類,由於所有的類型都從System.Object類型派生,所以每個類型的每個對象(實例)都會有一組最基本的方法。
二、Object公開的實例方法
以下一派生自Object之后自帶的公開的實例方法:
上面4個方法其中Equals、ToString、GetHashCode這三個方法是虛方法,可重寫GetType是外部方法.下面來一一介紹:
1、Equals方法
如果兩個對象具有相同的值,就返回true,詳情請參考C# 對象相等性判斷和同一性判斷
2、GetHashCode方法
返回對象的值的哈希值,詳情請參考C# 對象哈希碼
3、ToString方法
默認返回類型的完整名稱(this.GetType().FullName)。例如,核心類型(如Boolean和Int32)類型重寫該方法來返回他們的值的字符串表示,另外處於調試的目地而重寫該方法.調用后獲得一個字符串,顯示對象各字段的值.代碼如下:
static void Main(string[] args) { var t = new Test { Name = "張三", Desc = "張三的描述", Age = 23 }; Console.WriteLine(t.ToString()); Console.ReadKey(); } public class Test { public string Name { get; set; } public string Desc { get; set; } public int Age { get; set; } public override string ToString() { var type = this.GetType(); PropertyInfo[] infos = type.GetProperties(); StringBuilder sb = new StringBuilder(); foreach (var property in infos) { if (property.GetIndexParameters().Length == 0) { string propertyName = property.Name; string propertyType = property.PropertyType.Name; var propertValue = property.GetValue(this); if (property.GetIndexParameters().Length == 0) sb.AppendFormat("屬性名:{0},屬性類型:{1},屬性值:{2}", propertyName, propertyType, propertValue); else sb.AppendFormat("當前屬性為索引屬性,屬性名為:{0},屬性值:{1}", propertyName, propertyType); sb.AppendLine(); } } return sb.ToString(); } }
4、GetType方法
返回從一個Type派生的一個類型的實例,指出調用GetType的那個對象是什么類型,返回的Type對象和反射類配合,獲取與對象的類型有關的元數據信息.GetType是非虛方法,目的是防止類重寫該方法,隱瞞起類型,破壞類型的安全性,代碼如下:
public class Program { static void Main(string[] args) { var p = new Person { Name = "張三", Age = 23 }; var t = p.GetType(); var properties = t.GetProperties(); foreach (var item in properties) { var propertyName = item.Name; var propertyVal = item.GetValue(p); Console.WriteLine("屬性名:{0},屬性值:{1}", propertyName, propertyVal); } Console.ReadKey(); } } public class Person { public string Name { get; set; } public int Age { get; set; } }
三、Object受保護的方法
1、MemberwiseClone方法
這個非虛方法創建類型的新實例,並將新對象的實例字段設於this對象的實例字段完全一致,返回對新實例的引用,代碼如下:
public class Program { static void Main(string[] args) { var p = new Person { Name = "張三", Age = 11 }; var t=p.Clone(); Console.WriteLine("this is Original object named p,the value of property named Name is {0},this value of property named Age is {1}", p.Name, p.Age); Console.WriteLine("this is clone object named t,the value of property named Name is {0},this value of property named Age is {1}", t.Name, t.Age); Console.ReadKey(); } } public class Person { public string Name { get; set; } public int Age { get; set; } public Person Clone() { return (Person)MemberwiseClone(); } }
2、Finalize方法
在垃圾回收器判斷對象應該作為垃圾被回收之后,在對象的內存實際被回收之前,會調用這個虛方法.需要在回收內存前執行清理工作的類型應該重寫該方法.