1. 程式人生 > 其它 >c# 反射呼叫方法及屬性總結

c# 反射呼叫方法及屬性總結

技術標籤:c#

ClassLibrary1.dll內容

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

namespace ClassLibrary1
{
    public class Class1
    {

        public int Number { get; set; } = 11;
         string Str { get; set; } = "abc"
; public int Add(int a,int b) { return a + b; } private int Multiply(int a,int b) { return a * b; } } }

呼叫

 public void LoadDLLFile()
        {
            //C:\Users\source\repos\WpfApp1\App1\bin\Debug\ClassLibrary1.dll
//方式1 dll檔名(當前目錄) // Assembly assembly = Assembly.Load("ClassLibrary1"); //方式2 完整路徑(檔案具體的路徑) // Assembly assembly = Assembly.LoadFile(@"C:\Users\source\repos\WpfApp1\App1\bin\Debug\ClassLibrary1.dll"); //方式3 完全限定名(當前目錄) Assembly
assembly = Assembly.LoadFrom("ClassLibrary1.dll"); //方式4 完整路徑(檔案具體的路徑) // Assembly assembly = Assembly.LoadFrom(@"C:\Users\source\repos\WpfApp1\App1\bin\Debug\ClassLibrary1.dll"); Type type = assembly.GetType("ClassLibrary1.Class1"); object oReflection = Activator.CreateInstance(type);//建立例項 MethodInfo methodInfo = type.GetMethod("Add"); PropertyInfo propertyInfo = type.GetProperty("Number"); object d = propertyInfo.GetValue(oReflection); // propertyInfo.SetValue(oReflection, 11);//設定屬性 // methodInfo.Invoke(oReflection,null);//呼叫無引數方法 object c= methodInfo.Invoke(oReflection, new object[] {3,4 });//呼叫有引數方法 //foreach (var type in assembly.GetTypes())//type.name找的是名稱空間下的類名 //{ // // Console.WriteLine(type.Name); // foreach (var method in type.GetMethods())//找的是類下的方法 // { // // Console.WriteLine(method.Name); // } //} }

呼叫方法或者屬性分為5步

  1. 載入DLL檔案 Assembly assembly = Assembly.LoadFrom(“ClassLibrary1.dll”);
  2. 獲取類名 Type type = assembly.GetType(“ClassLibrary1.Class1”);
  3. 建立例項 object oReflection = Activator.CreateInstance(type);
  4. 獲取方法例項或者屬性例項 MethodInfo,PropertyInfo
  5. 呼叫
    object d = propertyInfo.GetValue(oReflection);//獲取屬性
    // propertyInfo.SetValue(oReflection, 11);//設定屬性
    // methodInfo.Invoke(oReflection,null);//呼叫無引數方法
    object c= methodInfo.Invoke(oReflection, new object[] {3,4 });//呼叫有引數方法