下面代码(摘抄之别处,原创在哪不知)是采用TransparentProxy和RealProxy实现对象的动态代理。碍于其使用反射调用方法,所以就小试着将反射改成Expression以提高执行的效率。第15行就是原来代码中反射调用方法的关键代码。
1 using System.Runtime.Remoting.Proxies;2 using System.Runtime.Remoting.Messaging;3 //RealProxy4 public class MyRealProxy<T>:RealProxy5 {6 private T _target;7 public MyRealProxy(T target) : base(typeof(T))8 {9 this._target = target;
10 }
11 public override IMessage Invoke(IMessage msg)
12 {
13 PreProceede(msg);
14 IMethodCallMessage callMessage = (IMethodCallMessage)msg;
15 object returnValue = callMessage.MethodBase.Invoke(this._target, callMessage.Args);
16 PostProceede(msg);
17 return new ReturnMessage(returnValue, new object[0], 0, null, callMessage);
18 }
19 public void PreProceede(IMessage msg)
20 {
21 Console.WriteLine("方法执行前");
22 }
23 public void PostProceede(IMessage msg)
24 {
25 Console.WriteLine("方法执行后");
26 }
27 }
28 //TransparentProxy
29 public static class TransparentProxy
30 {
31 public static T Create<T>()
32 {
33 T instance = Activator.CreateInstance<T>();
34 MyRealProxy<T> realProxy = new MyRealProxy<T>(instance);
35 T transparentProxy = (T)realProxy.GetTransparentProxy();
36 return transparentProxy;
37 }
38 }
其他的辅助类
1 public class User 2 {3 public string Name { get; set; }4 public string PassWord { get; set; }5 }6 7 public interface IUserProcessor8 {9 void RegUser(User user);
10 }
11
12 public class UserProcessor : MarshalByRefObject, IUserProcessor
13 {
14 public void RegUser(User user)
15 {
16 Console.WriteLine("Already registered.");
17 }
18
19 public string RegUser2(User user)
20 {
21 Console.WriteLine("Already registered.");
22 return "OK";
23 }
24 }
25
26 public class RemotingProxy
27 {
28 public void Execute()
29 {
30 try
31 {
32 User user = new User() { Name = "HK", PassWord = "12345" };
33 UserProcessor userprocessor = TransparentProxy.Create<UserProcessor>();
34 userprocessor.RegUser(user);
35 Console.WriteLine(userprocessor.RegUser2(user));
36 }
37 catch (Exception ex)
38 {
39 throw ex;
40 }
41
42 }
43 }
将15行替换为如下Expression实现的代码。
分类: C#