1、先新建一个接口
public interface ProxyInterface
{
public void Exe(string str);
}
2、实现这个接口
public class ProxyInterfaceImpl : ProxyInterface
{
public ProxyInterfaceImpl()
{
}
public void Exe(string str)
{
Console.WriteLine($"Exe输出str:{str}");
}
}
3、新建代理工具类
/// <summary>
/// 代理工具类
/// </summary>
/// <typeparam name="T"></typeparam>
public class ProxyTool<T> : DispatchProxy
{
/// <summary>
/// 目标类
/// </summary>
public T? decorated { get; set; }
/// <summary>
/// 动作之后执行
/// </summary>
public Action<object?[]?>? _afterAction { get; set; }
/// <summary>
/// 动作之前执行
/// </summary>
public Action<object?[]?, object>? _beforeAction { get; set; }
/// <summary>
/// 创建代理实例
/// </summary>
/// <param name="decorated">代理的接口类型</param>
/// <param name="afterAction">方法执行前执行的事件</param>
/// <param name="beforeAction">方法执行后执行的事件</param>
/// <returns></returns>
public T Create(T decorated, Action<object?[]?> afterAction, Action<object?[]?, object> beforeAction)
{
object? proxy = Create<T, ProxyTool<T>>(); // 调用DispatchProxy 的Create 创建一个新的T
ProxyTool<T> proxyDecorator = (ProxyTool<T>)(proxy??new ProxyTool<T>());
proxyDecorator.decorated = decorated;
//把自定义的方法委托给代理类
proxyDecorator._afterAction = afterAction;
proxyDecorator._beforeAction = beforeAction;
return (T)(proxy??new object());
}
/// <summary>
/// 代理方法执行
/// </summary>
/// <param name="targetMethod"></param>
/// <param name="args"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
protected override object? Invoke(MethodInfo? targetMethod, object?[]? args)
{
object? result = string.Empty;
BeforeAction(args, result);
Console.WriteLine($"BeforeAction执行后:{result}");
result = targetMethod?.Invoke(decorated, args);
AfterAction(args);
return result;
}
/// <summary>
/// 执行之后
/// </summary>
/// <param name="args"></param>
private void AfterAction(object?[]? args)
{
_afterAction?.Invoke(args);
}
/// <summary>
/// 执行之前
/// </summary>
/// <param name="args"></param>
/// <param name="result"></param>
private void BeforeAction(object?[]? args, object? result)
{
_beforeAction?.Invoke(args, result??new object());
}
}
4、在测试方法中使用
ProxyTool<ProxyInterface> proxyTool = new ProxyTool<ProxyInterface>();
ProxyInterface testJob = new ProxyInterfaceImpl();
Action<object?[]?> afterAction = new Action<object?[]?>(str =>
{
Console.WriteLine($"之后执行,参数:{str?[0]}");
});
Action<object?[]?, object> beforeAction = new Action<object?[]?, object>((str, str1) =>
{
str1 += "+1";
Console.WriteLine($"之前执行,参数:{str?[0]},结果:{str1}");
});
testJob = proxyTool.Create(testJob, afterAction, beforeAction);
testJob.Exe("111");