反射學習系列3-反射執行個體應用

來源:互聯網
上載者:User

例子這個東西其實挺難弄得,弄個簡單的,雖然能說明問題但卻容易讓人覺得沒實用價值,弄個有實用價值卻又往往牽扯很多別的技術甚至牽扯很多商務邏輯,看起來很複雜很難懂。在這裡我盡量追求幾個有實用價值又不複雜的例子。

1、使用反射通過讀取設定檔來動態建立相關類的對象

我們先來看看Main函數和需要動態載入的對象在同一個程式集的情況

結構圖:

介面

interface ILog
  {
    bool Write(string message);
    bool Write(Exception ex);
  }

TextFileLog

class TextFileLog : ILog
  {
    public bool Write(string message)
    {
      string fileDir = ConfigurationManager.AppSettings["LogTarget"].ToString();
      using (StreamWriter w = File.AppendText(fileDir))
      {
        // w.Write(" Log Entry : ");
        w.WriteLine("發生時間{0}", DateTime.Now.ToLocalTime().ToString());
        w.WriteLine("日誌內容為:{0}", message);
        w.WriteLine("-------------------------------");
        // Update the underlying file.
        w.Flush();
        w.Close();
      }
      return true;
    }
    public bool Write(Exception ex)
    {

      Write(ex.Message);
      return true;
    }
  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.