因最近工做須要一個動態的權限配置功能,具體實現邏輯是c#的動態代理功能,廢話很少說,直接乾貨。
需求:c#
從本篇開始咱們使用動態代理完成一個案例,包含動態權限控制的核心功能。ide
c#實現動態代理能夠使用.net framework 中提供的RealProxy類。this
能夠看到RealProxy是一個抽象類,其中Invoke是必需要重寫的,咱們嘗試重寫下RealProxy。spa
public class Proxy : RealProxy { public Proxy(Type t) : base(t) { } public override IMessage Invoke(IMessage msg) { throw new NotImplementedException(); } }
如今咱們擁有本身的代理類了,咱們須要一個「被代理」的對象,因而。.net
//被代理的類必定要繼承自MarshalByRefObject public class Plane : MarshalByRefObject { public void Fly() { Console.WriteLine("fly"); } }
準備工做都作完了,究竟要如何實現代理,咱們能夠經過RealProxy的GetTransparntProxy()方法來實現。代理
因而調試
static void Main(string[] args) { Proxy proxy = new Proxy(typeof(Plane), new Plane()); Plane plane = (Plane)proxy.GetTransparentProxy(); plane.Fly(); }
接下來調試運行,代碼執行到fly()方法,在invoke方法拋出異常,能夠看出在msg參數中找到咱們執行的方法信息與參數。代理模式的原理就是如此,經過代理類的代理方法去執行被代理類的方法。code
接下來咱們利用msg的參數信息去調用fly()方法。對象
public class Proxy : RealProxy { public Plane instance = null; public Proxy(Type t, Plane plane) : base(t) { this.instance = plane; } public override IMessage Invoke(IMessage msg) { Console.WriteLine("代理方法"); var methodCall = (IMethodCallMessage)msg; var result = methodCall.MethodBase.Invoke(instance, methodCall.Args); return new ReturnMessage(result, null, 0, methodCall.LogicalCallContext, methodCall); } }
運行結果blog
好了,咱們能夠看到代理方法已經生效了,這也是最最核心的功能。
注:雖然圖片來自csdn,但依然是本人在csdn的原創