小编use*_*878的帖子

如何在Castle.DynamicProxy中使用IInterceptor?

我写了一个这样的例子

简单计算器类:

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

17
推荐指数
2
解决办法
1万
查看次数

在C#中获取属性(反射)的最快方法

我想知道从对象的属性中获取价值的最快方法(仅针对此问题)是什么?

经过一番搜索,我在这个网站上看到了@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)

c# reflection delegates properties reflection.emit

4
推荐指数
1
解决办法
4623
查看次数