作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个类似打击的 IInterceptionBehavior:
public class TraceBehavior : IInterceptionBehavior
{
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
Console.WriteLine(string.Format("Invoke method:{0}",input.MethodBase.ToString()));
IMethodReturn result = getNext()(input, getNext);
if (result.Exception == null)
{
Console.WriteLine("Invoke successful!");
}
else
{
Console.WriteLine(string.Format("Invoke faild, error: {0}", result.Exception.Message));
result.Exception = null;
}
return result;
}
public bool WillExecute { get { return true; } }
}
无论我是否将其放在方法上,总是会抛出异常。谁能帮帮我?
最佳答案
代码看起来不错,但您没有说明如何注册拦截以及如何调用对象。
假设正在调用拦截,那么如果我猜测调用的方法将返回一个值类型并且 IMethodReturn.ReturnValue
为 null,这将导致 NullReferenceException
.
如果是这种情况,那么返回值类型的默认值可能会解决您的问题:
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
Console.WriteLine(string.Format("Invoke method:{0}", input.MethodBase.ToString()));
IMethodReturn result = getNext()(input, getNext);
if (result.Exception == null)
{
Console.WriteLine("Invoke successful!");
}
else
{
Console.WriteLine(string.Format("Invoke faild, error: {0}", result.Exception.Message));
result.Exception = null;
Type type = ((MethodInfo)input.MethodBase).ReturnType;
if (type.IsValueType)
{
result.ReturnValue = Activator.CreateInstance(type);
}
}
return result;
}
关于c# - 如何通过 IInterceptionBehavior 吞下异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8036559/
我正在尝试测试 IInterceptionBehavior 的实现: public class LoggingInterceptorBehavior : IInterceptionBehavior {
我有一个类似打击的 IInterceptionBehavior: public class TraceBehavior : IInterceptionBehavior { public IEn
Unity 似乎提供了两种不同的途径来实现 AoP 功能。 问题是为什么?有什么区别?每种方法的优缺点是什么? 例如使用 ICallHandler: unity.Configure() .AddMat
我是一名优秀的程序员,十分优秀!