我有一个从抽象基类派生的对象,我想拦截对象上的一个方法。
DynamicProxy是否支持此方案?我似乎只能通过接口或没有目标创建代理,但不能通过抽象基类和目标
创建代理public abstract class Sandwich
{
public abstract void ShareWithFriend();
}
public sealed class PastramiSandwich : Sandwich
{
public override void ShareWithFriend()
{
throw new NotSupportedException("No way, dude");
}
}
class SandwichInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
try
{
invocation.Proceed();
}
catch (NotSupportedException)
{
// too bad
}
}
}
internal class Program
{
private static void Main()
{
var sandwich = new PastramiSandwich();
var generator = new ProxyGenerator();
// throws ArgumentException("specified type is not an interface")
var proxy1 = generator.CreateInterfaceProxyWithTarget<Sandwich>(
sandwich,
new SandwichInterceptor());
proxy1.ShareWithFriend();
// does not accept a target
var proxy2 = generator.CreateClassProxy<Sandwich>(
/* sandwich?, */
new SandwichInterceptor());
// hence the method call fails in the interceptor
proxy2.ShareWithFriend();
}
}
答案 0 :(得分:0)
这有效:
var proxy1 = generator.CreateClassProxyWithTarget<Sandwich>(
sandwich,
new SandwichInterceptor());
proxy1.ShareWithFriend();