反射 C#

1.寫一個類,編譯成dll

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReflectTest
{
    public class TestClass
    {
        public int Totalizator(int a,int b)
        {
            return a + b;
        }

    }
}


2.編譯成dll取出,放在E:\Project\Dll目錄下,取名:ReflectTest.dll

3.反射調用dll中的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ExamplePro
{
    class Program
    {
        static void Main(string[] args)
        {
            //從Dll中加載
            Assembly ass = Assembly.LoadFile(@"E:\Project\Dll\ReflectTest.dll");
            //獲取類型
            Type Cltype= ass.GetType("ReflectTest.TestClass");
            object reflectObj = Activator.CreateInstance(Cltype,null);

            //使用MethodInfo 和Invoke 調用方法
            MethodInfo displayInfoMethod = Cltype.GetMethod("Totalizator");
            object data= displayInfoMethod.Invoke(reflectObj, new object[] {1,2});
            int intData = Int32.Parse(data.ToString());
            Console.WriteLine("反射調用Totalizator方法得到:" + intData.ToString());
            Console.ReadKey();
        }
    }
}


運行:


發佈了45 篇原創文章 · 獲贊 53 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章