【发布时间】:2011-09-01 18:49:03
【问题描述】:
我有一个从抽象基类派生的对象,我想截取该对象的方法。
DynamicProxy 是否支持这种情况?我似乎只能通过接口或没有目标来创建代理,但不能通过抽象基类 with 一个目标
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();
}
}
【问题讨论】:
标签: abstract-class castle-dynamicproxy