天天看點

C#反射學習

這天都在學習c#的反射原理,網上的資料很多。以前聽說反射也僅僅是在《大話設計模式》裡面直到一點點,了解不深。

開始我還不知道反射到底有什麼好處,後來我才知道利用反射我們可以在運作時的時候通過變量來執行個體化類的執行個體。可以有效避免了很多的邏輯判斷。

以下是我的測試的代碼:

using System;

using System.Collections.Generic;

using System.Text;

using System.Reflection;    //反射需要引用的命名空間

namespace 反射原理

{

    class Program

    {       

        static void(string[] args)

        {

            string str = Console.ReadLine();

            Icon i = ConFactory.ReturnCon(str);

            i.OutputStr();

            Console.ReadKey();

        }

    }

    class ConFactory

    {

        private static readonly string AssemblyName = "反射原理";    //程式及

        public static Icon ReturnCon(string str)   //str參數是指類名

            string ClassName = AssemblyName + "." + str;

            return (Icon)Assembly.Load(AssemblyName).CreateInstance(ClassName);   //生成特定類的執行個體,然後轉換為接口傳回

    interface Icon

        void OutputStr();

    class PersonCon : Icon

        public void OutputStr()

            Console.WriteLine("PersonCon");

    class WorldCon : Icon

            Console.WriteLine("WorldCon");

}

這樣我們可以通過讀取外部的配置檔案來對我們的變量進行指派,然後通過它來執行個體化特指的類。這招在多資料庫的應用特别有效。我們隻需要修改配置檔案就可以達到更換資料庫的目的。有效降低了類之間的耦合,更靈活,更容易修改…