當(dāng)前位置:首頁(yè) > IT技術(shù) > Windows編程 > 正文

c#代碼的執(zhí)行過(guò)程及反射
2021-10-18 17:42:29


0.c#代碼的執(zhí)行過(guò)程:

c#(編譯器)-->dll/exe(metadata/IL)-->CRL-->機(jī)器碼


1. appsettings.json配置文件配置要訪問(wèn)的類和dll

"ReflictionConfig": "Zhaoxi.AspNetCore.DB.MySql.MySqlHelper,Zhaoxi.AspNetCore.DB.MySql.dll"

2.代碼讀取dll,實(shí)例化一個(gè)配置類的對(duì)象

public static IDBHelper CreateInstance()

{

string ReflictionConfig = CustomConfigManager.GetConfig("ReflictionConfig");

string tyepName= ReflictionConfig.Split(",")[0];

string dllName = ReflictionConfig.Split(",")[1];

//Assembly assembly = Assembly.Load(dllName); //Dll名稱,不需要后綴

Assembly assembly3 = Assembly.LoadFrom(dllName); //dll名稱(需要后綴)


Type type = assembly3.GetType(tyepName);

object obj = Activator.CreateInstance(type);

return obj as IDBHelper;

}

3. 反射可以突破方法的權(quán)限限制

100_000_000

4. 反射性能并不會(huì)消耗多大,100萬(wàn)次循環(huán)和普通方法相差3倍的時(shí)間,

單例模式=是一種常見類的寫法,

public class SingletonA

{

//私有成員,使用時(shí)分配內(nèi)存

private static SingletonA _instance = null;

//私有構(gòu)造,杜絕直接new類

private SingletonA() { }

//獲取實(shí)例

public static SingletonA GetInstance ()

{

if (_instance == null)

{

_instance = new SingletonA();

}

return _instance;

}

}


本文摘自 :https://blog.51cto.com/u

開通會(huì)員,享受整站包年服務(wù)立即開通 >