我写了一个这样的例子
简单计算器类:
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
Run Code Online (Sandbox Code Playgroud)
实现了DynamicProxy提供的"IInterceptor"
[Serializable]
public abstract class Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
ExecuteBefore(invocation);
invocation.Proceed();
ExecuteAfter(invocation);
}
protected abstract void ExecuteAfter(IInvocation invocation);
protected abstract void ExecuteBefore(IInvocation invocation);
}
Run Code Online (Sandbox Code Playgroud)
创建了一个Interceptor类,并继承自"Interceptor"类
public class CalculatorInterceptor : Interceptor
{
protected override void ExecuteBefore(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("Start");
}
protected override void ExecuteAfter(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("End");
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我用它不工作!
static void Main(string[] args)
{
ProxyGenerator generator …Run Code Online (Sandbox Code Playgroud) c# castle-dynamicproxy dynamic-proxy interceptor interception
我想知道从对象的属性中获取价值的最快方法(仅针对此问题)是什么?
经过一番搜索,我在这个网站上看到了@MarkGravell的帖子
他写了这段代码:
using System;
using System.Reflection;
using System.Reflection.Emit;
public class Foo
{
public Foo(int bar)
{
Bar = bar;
}
private int Bar { get; set; }
}
static class Program {
static void Main()
{
var method = new DynamicMethod("cheat", typeof(int),
new[] { typeof(object) }, typeof(Foo), true);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, typeof(Foo));
il.Emit(OpCodes.Callvirt, typeof(Foo).GetProperty("Bar",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
).GetGetMethod(true));
il.Emit(OpCodes.Ret);
var func = (Func<object, int>)method.CreateDelegate(
typeof(Func<object, int>));
var obj = new Foo(123);
Console.WriteLine(func(obj));
}
} …Run Code Online (Sandbox Code Playgroud)