我正在使用大量未记录的 Castle 动态代理系统。我已经设法让它完成我想要的几乎所有事情,除了一件事:如何使代理方法抛出异常而不是返回值?
public sealed class MyInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (CheckArgs(invocation.Arguments))
{
invocation.ReturnValue = DoRealWork(invocation.Arguments);
}
else
{
invocation.Exception = new InvalidOperationException(); // How?
}
}
}
从被代理对象的角度来看,拦截器是不可见的;它只是调用自己的虚拟方法,DynamicProxy 在返回之前调用正确的拦截器方法ReturnValue
给来电者。
因此,如果你想抛出异常,只需从拦截器中抛出即可:
if (CheckArgs(invocation.Arguments))
{
invocation.ReturnValue = DoRealWork(invocation.Arguments);
}
else
{
throw new InvalidOperationException();
}
从调用者的角度来看,这将是被调用方法中的异常。
编辑评论:
关于生成器中抛出的异常的类型,我有正确的类型,而不是包装器:
public interface IDummy
{
string DoSomething();
}
public class Dummy: IDummy {
public virtual string DoSomething()
{
return string.Empty;
}
}
public class MyCustomException : Exception {}
public class CustomIntercept: IInterceptor
{
public void Intercept(IInvocation invocation)
{
throw new MyCustomException();
}
}
internal class Program
{
private static void Main(string[] args)
{
var pg = new ProxyGenerator();
GetValue(pg.CreateInterfaceProxyWithoutTarget<IDummy>(new CustomIntercept()));
GetValue(pg.CreateClassProxy<Dummy>(new CustomIntercept()));
GetValue(pg.CreateClassProxyWithTarget<Dummy>(new Dummy(), new CustomIntercept()));
GetValue(pg.CreateInterfaceProxyWithTarget<IDummy>(new Dummy(), new CustomIntercept()));
}
private static void GetValue(IDummy dummy)
{
try
{
dummy.DoSomething();
}
catch (Exception e)
{
Console.WriteLine(e.GetType().Name);
}
}
}
所有四个输出都是MyCustomException
您能否确保 TargetInitationException 不是来自您自己的代码?您使用的是哪个版本的DynamicProxy(我使用的是Castle.Core 3.2中的版本)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)