C# 反射總結 獲取 命名空間 類名 方法名


一、獲取 命名空間 類名 方法名

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

namespace GetMethodNameSpace
{
    class Program
    {
        public static string GetMethodInfo()
        {
            string str = "";
            //取得當前方法命名空間
            str += "命名空間名:" + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace + "\n";
            //取得當前方法類全名
            str += "類名:" + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "\n";
            //取得當前方法名
            str += "方法名:" + System.Reflection.MethodBase.GetCurrentMethod().Name + "\n";
            str += "\n";

            StackTrace ss = new StackTrace(true);
            MethodBase mb = ss.GetFrame(1).GetMethod();
            //取得父方法命名空間
            str += mb.DeclaringType.Namespace + "\n";
            //取得父方法類名
            str += mb.DeclaringType.Name + "\n";
            //取得父方法類全名
            str += mb.DeclaringType.FullName + "\n";
            //取得父方法名
            str += mb.Name + "\n";
            return str;
        }

        public static void Main()
        {
            Console.WriteLine(GetMethodInfo());

            Console.ReadKey();
        }
    }
}

 二、利用反射動態加載dll

頭部引用加:

using System.Reflection;
Assembly asm = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory+ "/DeclareDLL/YunDouTaxLib.dll");////我們要調用的dll文件路徑
//加載dll后,需要使用dll中某類.
Type t = asm.GetType("namespace.classname");//獲取類名,必須 命名空間+類名  

 //實例化類型
object o = Activator.CreateInstance(t);

//得到要調用的某類型的方法
MethodInfo method = t.GetMethod("functionname");//functionname:方法名字

object[] obj =
{
     Parameters[0].TaxpayerName,
     Parameters[0].TaxpayerTaxCode,
     Parameters[0].CAPassword
};
//對方法進行調用
var keyData = method.Invoke(o, obj);//param為方法參數object數組

三,沒有Assembly.LoadFrom 需要在程序中加引用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM