C# System.Object基類

  System.Object在.Net中是全部類型的基類,任何類型都直接或間接地繼承自System.Object。沒有指定基類的類型都默認繼承於System.Object。html

基類特性

  正因爲全部的類型都繼承於System.Object。所以,全部的類型都具備下面這些特性:安全

  •   GetType()方法,獲取對象的類型。
  •   Equals、ReferenceEquals和==,判斷對象是否相等。
  •   ToString()方法,獲取對象的字符串信息,默認返回對象帶命名空間的全名。
  •   MemberwiseClone()方法,對象實例的淺拷貝。
  •   GetHashCode()方法,獲取對象的值的散列碼。
  •   Finalize()方法,在垃圾回收時,進行資源管理。

ToString()解析

  ToString()是一個虛方法,用於返回對象的字符串表示,在Object類型的實現相似於:ide

  public virtual string ToString()
  {
    return this.GetType().FullName.ToString();              
  }

  咱們很容易就可以對ToString()進行覆寫,以實現咱們想要的效果:post

複製代碼
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(new Person().ToString());     //輸出 我是一個Person類!

            Console.ReadKey();
        }
    }

    public class Person
    {
        public override string ToString()
        {
            return "我是一個Person類!";
        }
    }
複製代碼

  .Net中不少類型也實現了對ToString()方法的覆寫,例如Boolean類型就覆寫了ToString()方法來返回真或假的字符串:this

複製代碼
    public override string ToString()
    {
        if(!this)
        {
            return "False";
        }
        return "True";
    }
複製代碼

  在處理字符串格式化、語言文化方面。ToString()沒有太多的辦法。解決的辦法是實現IFormattable接口。IFormattable接口的定義以下:url

    public interface IFormattable
    {
        string ToString(string format, System.IFormatProvider formatProvider);
    }

  參數format指定要格式化的方式,而參數formatProvider則提供了特定語言文化信息。大部分.Net基本類型都實現了IFormattable接口,用於實現更靈活的字符串信息輸出。spa

GetType()解析

  GetType()方法,不是虛方法,用於在運行時經過查詢對象元數據來獲取對象的運行時類型。子類沒法經過覆寫GetType()而篡改類型信息,從而保證了類型安全。code

  示例:orm

複製代碼
        static void Main(string[] args)
        {
            Person p = new Person();
            Type t = p.GetType();    //實例方法
            Console.WriteLine(t.FullName);  //輸出對象所在類的全稱

            Console.ReadKey();
        }
複製代碼

  其實,這個方法就是返回一個System.Type類的對象,該對象在反射中經常使用到。反射不是本文的範疇,再也不敘述。htm

  在.Net中,下面的方法可以實現與System.Object的GetType()方法相同的效果:

  •   Type.GetType()靜態方法
  •   typeof運算符

  下面說說它們二者的區別:

  Type.GetType()是非強類型方法,支持輸入字符串做爲參數;而typeof運算符支持強類型。

  Type t = Type.GetType("ConsoleApplication.Person");
  Type t = typeof(ConsoleApplication.Person);

  另外,要特別注意的就是,只有Type.GetType()支持跨程序集反射,解決動態引用;而typeof只能支持靜態引用。

    Assembly ass = Assembly.LoadFrom(@"C:\Model.dll");
    Type t = ass.GetType("Model.Person");

  關於他們之間的區別,能夠查看:http://www.cnblogs.com/mingxuantongxue/p/3730076.html

  其餘方法的範疇歸屬,全均可以另起一篇文章。待我想一想。

相關文章
相關標籤/搜索