C#使用反射開發外掛程式

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   使用   ar   for   檔案   

當開發外掛程式的時候需要用到反射,在用戶端動態載入遍曆程式集,並調用每個程式集的方法。

 

建立一個控制台應用程式,首先設計一個介面:

    public interface ISay
    {
        void SaySth();
    }

 

在控制台應用程式下建立Plugins檔案夾,控制台的可執行檔和所有組件檔都產生在這裡。右鍵控制台項目--"屬性"--"產生",把"輸出路徑"設定成Plugins檔案夾。

 

建立類庫項目Assembly1,添加對控制台項目的引用,並建立實現ISay介面的類:

namespace Assembly1
{
    public class OneSay : ISay
    {
        public void SaySth()
        {
            Console.WriteLine("我來自程式集1");
        }
    }
}

 

右鍵類庫項目Assembly1--"屬性"--"產生",把"輸出路徑"設定成Plugins檔案夾,並產生類庫項目Assembly1。

 

用戶端需要找到所有程式集中所有實現ISay介面的類。其基本思路是:
→找到Plugins檔案夾下所有dll尾碼的檔案
→遍曆這些檔案,根據檔案名稱動態載入程式集
→遍曆程式集中實現ISay介面的類型,並儲存到ISay類型的集合中
→用戶端遍曆ISay類型的集合,調用ISay的介面方法

    class Program
    {
        static void Main(string[] args)
        {
            foreach (var say in GetSpeakers())
            {
                say.SaySth();
            }
        }
        static List<ISay> GetSpeakers()
        {
            List<ISay> result = new List<ISay>();
            //擷取項目根目錄下的Plugins檔案夾
            string dir = Directory.GetCurrentDirectory();
            //遍曆目標檔案夾中包含dll尾碼的檔案
            foreach (var file in Directory.GetFiles(dir + @"\", "*.dll"))
            {
                //載入程式集
                var asm = Assembly.LoadFrom(file);
                //遍曆程式集中的類型
                foreach (var type in asm.GetTypes())
                {
                    //如果是ISay介面
                    if (type.GetInterfaces().Contains(typeof (ISay)))
                    {
                        //建立介面類型執行個體
                        var isay = Activator.CreateInstance(type) as ISay;
                        if (isay != null)
                        {
                            result.Add(isay);
                        }
                    }
                }
            }
            return result;
        }

 

再建立一個類庫項目Assembly2,添加對控制台項目的引用,並建立實現ISay介面的類:

namespace Assembly2
{
    public class TwoSay : ISay
    {
        public void SaySth()
        {
            Console.WriteLine("我來自程式集2");
        }
    }
}

 

右鍵類庫項目Assembly2--"屬性"--"產生",把"輸出路徑"設定成Plugins檔案夾,並產生類庫項目Assembly2。

 

再次運行控制台項目。

C#使用反射開發外掛程式

聯繫我們

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